# Using foreach to draw a line

I desperately need some help with the following: In this MWE I would like to draw a circle (ideally: a vertical line) at an x value coming from a foreach command.

\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
width=10cm,
height=10cm,
grid=major,
xlabel=$x$,
ylabel=$f(x)$,
xmin=-4,
xmax=3,
]

\foreach \xj in {
{(-3,0)},
{(-2,1)}
} {
%\draw \xj -- (0,0);
}

\foreach \xj in {-5,-4,...,5} {
%\draw (\xj,0.5) -- (\xj, 1);
}

\end{axis}
\end{tikzpicture}

\end{document}


The addplot command is used to being able to adjust the axis. For some reason, that does not work unless there is this addplot present. But that is not the issue. The issue is this:

The first foreach command gives me errors, but compiles nonetheless. However, the circle that is drawn is at the left border of the plot domain. Theres something wrong here...

The second foreach command throws so many errors that the file doesn't compile anymore. I have no idea why this does not work, but it is because the \x is in the definition of the draw command. If changing the \x to lets say -2.5, the file compiles fine.

Any ideas why this does not work like I hoped it would, and any ideas on how to fix this issue?

You do not have to change the \foreach command. If you use the \edef\temp{\noexpand ...} trick you can also work with the standard \foreach command. But there is an even simpler option: use foreach in the path.

\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
width=10cm,
height=10cm,
grid=major,
xlabel=$x$,
ylabel=$f(x)$,
xmin=-4,
xmax=3,
]

\draw foreach \xj in {
{(-3,0)},
{(-2,1)}
} {

}
foreach \xj in {-5,-4,...,5} {(\xj,0.5) circle[radius=1em]};

\end{axis}
\end{tikzpicture}
\end{document}


• Thanks for your help, I got it to work! Apparently, you can even foreach in a foreach. What actually also broke my particular example was giving each point as (\xj/\yj), instead of xj/yj, (without the brackets). In case someone has a similar problem, this works: \draw foreach \offset in {-1,0,1} {foreach \xj/\yj in {-2/0, -1/0.2, 0/0.4} {(\xj+\offset,\yj) -- (\xj+\offset,\yj+1)}}; Dec 21 '20 at 11:24

Loop \foreach doesn't work in pgfplots. In it you need to use adopted version of it as are \pgfplotsforeachungrouped and \pgfplotsinvokeforeach. For details see documentation for pgfplots, page 544 -- 545 (section 8.1 Utility Commands):

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=10cm,
height=10cm,
grid=major,
xlabel=$x$,
ylabel=$f(x)$,
xmin=-4,
xmax=3,
]

\pgfplotsforeachungrouped \x/\y in {-3/0, -2/1}%
{
\temp
}

\pgfplotsinvokeforeach{-5,-4,...,5}%
{
`