1

I get an error when running the following code:

\begin{frame}
\frametitle{MWE}
\begin{tikzpicture}
    \begin{axis}[declare function={f(\x)=\x^3-3*\x^2+\x;}]
        \addplot[red] {f(x)};
        \pgfmathsetmacro{\a}{-0.15}
        \coordinate (A) at (axis cs: \a, {f(\a)});
        \foreach \dx in {1.0, 0.5, 0.2, 0.1, 0.05}{
            \coordinate (b) at (axis cs: {\a+\dx}, {f(\a+\dx)});
        }
    \end{axis}
\end{tikzpicture}
\end{frame}

The error: `! Undefined control sequence. axis cs: {\a +\dx

}, {f(\a +\dx )}`

The \coordinate command outside the loop works (i.e. \coordinate (A) at (axis cs: \a, {f(\a)});).

I would appreciate any help finding out the issue.

pelegs
  • 267
  • What control sequence is undefined? You can see it in the log file: the line is broken at this sequence. But we cannot see this because you didn't presented the multi-line part of the log file (a few lines after the message "undefined control sequence"). – wipet Jun 03 '21 at 14:29
  • I edited the question. It is as follows:<argument> axis cs: {\a +\dx }, {f(\a +\dx )} l.18 \end{axis} – pelegs Jun 03 '21 at 14:35
  • 1
    check this one: https://tex.stackexchange.com/questions/170664/foreach-not-behaving-in-axis-environment – Gunter Jun 03 '21 at 14:40

1 Answers1

2

based on \foreach not behaving in axis environment, the following solution seems to work

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[declare function={f(\x)=\x^3-3*\x^2+\x;}]
        \addplot[red] {f(x)};
        \pgfmathsetmacro{\a}{-0.15}
        \coordinate (A) at (axis cs: \a, {f(\a)});
        \foreach \dx in {1.0, 0.5, 0.2, 0.1, 0.05}{
            \edef\temp{\noexpand\coordinate (b) at (axis cs: {\a+\dx}, {f(\a+\dx)});}
            \temp
        }
    \end{axis}
\end{tikzpicture}
\end{document}

EDIT:

In my first attempt I was a bit hesitant about the second approach provided in the link above. But now I tested that one as well. Both work. Actually I would prefer the second one, as it does not include so many "weird" commands.

\documentclass[tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}
        \begin{axis}[declare function={f(\x)=\x^3-3*\x^2+\x;}]
            \addplot[red] {f(x)};
            \pgfmathsetmacro{\a}{-0.15}
            \coordinate (A) at (axis cs: \a, {f(\a)});
            \pgfplotsinvokeforeach{1.0, 0.5, 0.2, 0.1, 0.05}{
                \coordinate (b) at (axis cs: {\a+#1}, {f(\a+#1)});
            }
        \end{axis}
    \end{tikzpicture}
\end{document}
Gunter
  • 443