[Tex/LaTex] Use TikZ foreach variable in node

foreachpgfplots

This MWE

\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}[scale=0.75]
    \begin{axis}[ylabel=Y-Axis, xlabel=X-Axis
, xmin=2, xmax=10, ymin=0, ymax=12, clip=false, axis y line*=right]
    \foreach \blah in {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{
        \addplot[mark=none, domain=2:10, thick] {-ln(\blah/x^2)/ln(x)} node [pos=0,left] {$c_2=$}; %Varying c_2 values
    }
    \end{axis}
\end{tikzpicture}

\end{document}

produces this result

Graph showing unlabeled c_2 values

Note that the c_2= nodes on the left-hand side have no values on by the equal sign. I thought I could fix that by using

\addplot[mark=none, domain=2:10, thick] {-ln(\blah/x^2)/ln(x)} node [pos=0,left] {$c_2=$\blah}; %Varying c_2 values

But this doesn't work because PDFLaTeX tells me that I have an "Undefined control sequence." while referring to \blah.

How can I get this to work?

Best Answer

PGFPlots includes a special looping mechanism that avoids problems with unexpanded macros:

\pgfplotsinvokeforeach{<list>}{
    < code where the list element is available as #1 >
}

In your case, you would write

\pgfplotsinvokeforeach {0.9,0.5,0.2,0.1,0.05,0.02,0.01,0.005}{
        \addplot[mark=none, domain=2:10, thick] {-ln(#1/x^2)/ln(x)} node [pos=0,left] {$c_2=#1$}; 
}

to get