1

The code below works fine

\begin{tikzpicture}
\begin{axis}
[ 
      ticks = none, axis lines = middle,
      xmin = -5, xmax = 5,
      ymin = -5, ymax = 5,
    ]
    \foreach \p in {1,2}{
        \draw[red] (-5,1)--(5,1);
    }
\end{axis}
\end{tikzpicture}

However, as soon as I try to use the variable \p inside the loop, as in

\begin{tikzpicture}
\begin{axis}
[ 
      ticks = none, axis lines = middle,
      xmin = -5, xmax = 5,
      ymin = -5, ymax = 5,
    ]
    \foreach \p in {1,2}{
        \draw[red] (-5,\p)--(5,\p);
    }
\end{axis}
\end{tikzpicture}

I get an undefined control sequence error. This persists no matter what I use instead of \p.

1

Welcome to TeX-SE! Notice that pgfplots does a lot of service in the background, which is why some variantes of \foreach may not work in an axis environment. These things are explained in detail in section 8.1 Utility Commands of the pgfplots manual. Long story short for this case: use \pgfplotsinvokeforeach instead.

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}
[ 
      ticks = none, axis lines = middle,
      xmin = -5, xmax = 5,
      ymin = -5, ymax = 5,
    ]
    \pgfplotsinvokeforeach{1,2}{
        \draw[red] (-5,#1)--(5,#1);
    }
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

There are situations in which you really want to use the traditional \foreach loop. In those you can you can use this answer to get

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\begin{axis}
[ 
      ticks = none, axis lines = middle,
      xmin = -5, xmax = 5,
      ymin = -5, ymax = 5,
    ]
    \foreach \p in {1,2}{
        \edef\temp{\noexpand\draw[red] (-5,\p)--(5,\p);}
        \temp
    }
\end{axis}
\end{tikzpicture}
\end{document}

Side-remark: try to avoid calling the loop variable \p, \n, \x or \y if you consider making use of the calc library because there these macros have their own meanings.

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.