Why doesn’t this \foreach work

for looploopspgfplotstabletikz-pgf

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}
\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    grid=major,
    xmin = 0, xmax = 6,
    ]
    \addplot[red, domain=0:6, samples=10,]{x};
    \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[red, domain=0:6, samples=10,]{\w * x};
    \addplot[blue, mark=square, ycomb] coordinates {(\w, \w^2 - 1)};
    }
\end{axis}
\end{tikzpicture}

enter image description here

Best Answer

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:

enter image description here

Code:

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

\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},
    ]
    \addplot[red, domain=0:6, samples=10,]{x};
    
    \pgfplotsinvokeforeach{1,2,3,4,5} {
        \node[]  at (#1 , 1)  {Hello};
    }
\end{axis}
\end{tikzpicture}
Related Question