1

I am trying to use some of the TikZ and PGFMath tools (e.g. \pgfmathdeclarefunction and \foreach) to make plotting things easier. However, I can't get the following code to compile. There seems to be a bad interaction between the \addplot command and the \foreach command. It compiles fine when either of those is commented out, but not when they are both present.

\documentclass{beamer}
\usepackage{pgfplots}
\pgfmathdeclarefunction{f}{1}{%
    \pgfmathparse{0.3+0.3*#1-1*#1^2+0.65*#1^3}%
}

\begin{document}

\begin{frame}
\begin{center}
\begin{tikzpicture}
\begin{axis}
    \addplot{{f(x)}} node(endofplot)[anchor=west]{$f$};
    \foreach \n in {8,12,16}
        \node [above] at (\n,0) {$\n$};
\end{axis}
\end{tikzpicture}
\end{center}
\end{frame}

\end{document}
2

Problem solved - the commands inside \foreach need to wrapped in \edef\temp{\noexpand and }\temp tags. I'll make this answer community wiki, so someone with actual TeX knowledge can explain why this works.

\documentclass{beamer}
\usepackage{pgfplots}
\pgfmathdeclarefunction{f}{1}{%
    \pgfmathparse{0.3+0.3*#1-1*#1^2+0.65*#1^3}%
}

\begin{document}

\begin{frame}
\begin{center}
\begin{tikzpicture}
\begin{axis}
    \addplot{{f(x)}} node(endofplot)[anchor=west]{$f$};
    \foreach \n in {8,12,16}
        \edef\temp{\noexpand
           \node [above] at (\n,0) {$\n$};
        }\temp
\end{axis}
\end{tikzpicture}
\end{center}
\end{frame}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.