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}

1 Answers1

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}

  • Per @muzimuzhi's comment, this answer by Christian Feuersänger explains why this works: https://tex.stackexchange.com/questions/69445/using-pgfplots-why-do-i-get-undefined-control-sequence-when-trying-to-use-a-f/71199#71199 – Jordan Mitchell Barrett Aug 08 '20 at 00:58