6

I'm finding some weird behavior with TikZ's \foreach within an \begin{axis} environment.

This works:

\foreach \x in {-2,-1,...,2} {
  \addplot[thick, domain=0.05+(\x*2-1)*pi/2:+(\x*2+1)*pi/2-0.05] (x, {tan(deg(x))}); 
}

but this doesn't:

\foreach \x in {-2,-1,...,2} {
  \draw (\x,-5) -- (\x,5);
}

It gives the error

! Undefined control sequence.
<argument> \x 
              ,-5
l.771     \end{axis}

Here's the really weird part: it only fails when the axis has defined bounds. For example, here's a MWE that works (but doesn't draw anything):

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis} % [ ymin=-3, ymax=3, xmin=-5, xmax=5]
    \foreach \q in {-2,-1,...,2} {
      \draw (axis cs: \q,-5) -- (axis cs: \q,5);
    }
  \end{axis}
\end{tikzpicture}
\end{document}

but removing the comment causes it to fail.

Why is this and how can I prevent it?

(My end goal is to draw five segments of the tangent function and their verical symptotes.)

2
  • Have you seen tex.stackexchange.com/questions/34197/asymptotes-in-a-plot? I'm not sure it will help with the for loop thing, though. Commented Mar 16, 2014 at 20:29
  • Yes, I've seen it, but it's next to impossible to get the tangent function to evaluate exactly at n*pi/2 because of floating point errors. In any case, I got the tangent function to plot fine with a for loop; it's the lines that are causing trouble.
    – wchargin
    Commented Mar 16, 2014 at 20:30

1 Answer 1

10

Pgfplots don't parse the drawing commands as TikZ do. It has to first gather all the paths to be drawn and then does some black magic for obtaining the maximum and minimum etc. Hence for such purposes you need to provide fully expanded path descriptions. In your first problematic one \x never replaced with its value so when pgfplots decide to read your paths it just sees \x which is not defined outside the loop. For that purpose, you have other means of looping and one given below.

Also you need to have axis cs to define the points otherwise they are not guaranteed to be in the visible area of the axis. Instead you can use the following;

\begin{tikzpicture}
\begin{axis}[ymax=5,ymin=-5,xmax=2.1,xmin=-2.1]
\pgfplotsinvokeforeach{-2,...,2}{
  \draw (axis cs:#1,-5) -- (axis cs:#1,5);
}
\end{axis}
\end{tikzpicture}

enter image description here

But if this is only for asymptotes, then you are better off with extra x ticks and grid options for extra ticks.

1
  • Ah - extra x ticks is a great idea. Thanks.
    – wchargin
    Commented Mar 16, 2014 at 20:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .