# Why doesn't this \foreach work?

I don't understand why this doesn't work. I changed x to y and z but it didn't work. Any ideas?

\documentclass[11pt]{article}
\usepackage{pgfplots,pgfplotstable}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
grid=major,
xmin = 0, xmax = 6,
]
\foreach \x in {1.,2.,3.,4.,5.}
\node[] at (\x , 1)  {Hello};
\end{axis}
\end{tikzpicture}
\end{document}


Added: but it works properly for \addplot provided the variable name is neither \xnor \y

\begin{tikzpicture}
\begin{axis}[
grid=major,
]
\foreach \w in {1,2,...,5} {
\addplot[blue, mark=square, ycomb] coordinates {(\w, \w^2 - 1)};
}
\end{axis}
\end{tikzpicture}


Another option is to use \pgfplotsinvokeforeach:

\pgfplotsinvokeforeach{1,2,3,4,5} {
\node[]  at (#1 , 1)  {Hello};
}


where the parameter is availalbe as #1. This yields:

### Code:

\documentclass[11pt]{article}
\usepackage{pgfplots,pgfplotstable}
%\usepgfplotslibrary{colormaps}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
grid=major,
xmin = 0, xmax = 6,
legend style={
legend pos= north west,},
legend style={%at={(0.5,0.95)},anchor=north,
legend columns=1},
]

\pgfplotsinvokeforeach{1,2,3,4,5} {
\node[]  at (#1 , 1)  {Hello};
}
\end{axis}
\end{tikzpicture}

• Cuold you please check my comment (with the ink) on the other answer ? Jan 18 at 8:43
• @Physor: That would make a very good separate question. I suspect it has to do with how nodes are created at the end of the axis environemnt, where as in the other question regarding a \foreach problem does not do the drawing in an axis environment. Jan 18 at 9:02
• As far as i unterstand your question, this osbecause \foreach works without special ptroblems on tikz pictures but not inside pgfplots' axis environment , where \pgfplotsinvokeforeach must ne used.
– Jhor
Jan 18 at 10:37
• i added something, maybe interesting! Jan 18 at 17:37
• @Physor: I still recommend that you post anohter question. Note that what you posted does not a drawing but calls an internal pgfplots function do do a graph. Jan 18 at 17:39

\x needs to be expanded, because it is in its own \foreach group and its value is thus effervescent. By expanding it first, the actual value of \x is passed to \node, rather than an indirect reference to \x, which does not persist.

\documentclass[11pt]{article}
\usepackage{pgfplots,pgfplotstable}
%\usepgfplotslibrary{colormaps}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
grid=major,
xmin = 0, xmax = 6,
legend style={
legend pos= north west,},
legend style={%at={(0.5,0.95)},anchor=north,
legend columns=1},
]

• What a maneuver! (\def\tmp{\node[] at (}), isn't there another way to use loops for nodes ? Jan 18 at 1:20
• @Physor I can think of several other ways, but each one is even uglier, LOL. The bottom line is the loop variable \x needs to be expanded as the argument to \node. Jan 18 at 1:34
• @Physor or  \foreach \x in {1.,2.,3.,4.,5.} { \edef\tmp{\noexpand \node[] at (\x , 1) {Hello}}\tmp;} Jan 18 at 6:44