[Tex/LaTex] TiKZ picture does not sit properly in `figure` environment

diagramsfloatstikz-pgf

This code:

\documentclass{tufte-handout}
\usepackage{tikz}

\begin{document}


\title{Lorem ipsum}
\author{me}
\date{now}
\maketitle

Lorem ipsum dolor sit amet, blah blah blah...

\begin{figure}

\begin{tikzpicture}

\def\spiral#1{%
  \pgfmathparse{int(#1)}%
  \ifnum\pgfmathresult>0
    \draw [help lines] (0,0) rectangle ++(-1,1);
    \begin{scope}[shift={(-1,1)}, rotate=90, scale=1/1.6180339887]
      \spiral{#1-1}
    \end{scope}
    \draw [red] (0,0) arc (0:90:1);
  \fi
}

\tikz[scale=2]{\spiral{12}}
\end{tikzpicture}
\caption{The golden spiral.}
\label{ref:golden_spiral}

\end{figure}

Sed tortor tellus, &c., &c.

\end{document}

produces this output:

Behold the odd placement of the diagram.

Obviously what I want is for the diagram to be where that big gap in the text is now. I've used tikzpicture in figures before, and it's worked properly, so presumably it's something about this diagram that's producing the problem, but I don't see what it is. How can I get that spiral to sit where it belongs?

Edit: this earlier post suggests that re-invoking tikz is the problem. Is that the issue here? And if so, how should I modify the line \tikz[scale=2]{\spiral{12}}? I tried removing it altogether, but that just meant that the diagram didn't appear at all.

Best Answer

You are mixing the definition of spiral and its use. Put the definition in preamble. Also, the second \tikz is not needed. Further, there are & without \. It should be \&c., \&c. and add [htb] to the options of figure environment.

\documentclass{tufte-handout}
\usepackage{tikz}

\def\spiral#1{%
  \pgfmathparse{int(#1)}%
  \ifnum\pgfmathresult>0
    \draw [help lines] (0,0) rectangle ++(-1,1);
    \begin{scope}[shift={(-1,1)}, rotate=90, scale=1/1.6180339887]
      \spiral{#1-1}
    \end{scope}
    \draw [red] (0,0) arc (0:90:1);
  \fi
}
\title{Lorem ipsum}
\author{me}
\date{now}
\begin{document}
\maketitle

Lorem ipsum dolor sit amet, blah blah blah...

\begin{figure}[htb]
\centering
\begin{tikzpicture}[scale=2]
\spiral{12}
\end{tikzpicture}
\caption{The golden spiral.}
\label{ref:golden_spiral}
\end{figure}

Or

\begin{figure}[htb]
\centering
\tikz[scale=2]{\spiral{12}}
\caption{The golden spiral.}
\label{ref:golden_spiral}
\end{figure}

Sed tortor tellus, \&c., \&c.

\end{document}

enter image description here

Also, I have put the title metadata etc in the preamble.

Related Question