2

I would like to plot a list of data and add according legend entries. I tried to use \foreach for tuples which is implemented in pgffor package and loaded with TikZ. Unfortunately, the second variable describing the label \clabel appears to be undefined for LaTeX. This construction seems to work if used outside \begin{axis} ... \end{axis}. Do I miss something essential regarding TikZ/PGF?

Minimal example

\documentclass[tikz,border=10pt]{standalone}
\usepackage{pgfplots}

\pgfplotsset{
    compat=1.16,
}

\begin{document}
\begin{tikzpicture}

    \begin{axis}[]
      \foreach \c/\clabel in {1/a, 2/b}
      {
        \addplot  {\c^2};
        \addlegendentry{ \clabel }
      };
    \end{axis}


\end{tikzpicture}
\end{document}
1

You need to expand \clabel as the argument for \addlegendentry, since the legend itself is created after the plots are complete. By that point, the local value of \clabel has been lost.

\documentclass[tikz,border=10pt]{standalone}
\usepackage{pgfplots}

\pgfplotsset{
    compat=1.16,
}

\begin{document}
\begin{tikzpicture}

    \begin{axis}[]
      \foreach \c/\clabel in {1/a, 2/b}
      {
        \addplot  {\c^2};
        \expandafter\addlegendentry\expandafter{\clabel};
      }
    \end{axis}


\end{tikzpicture}
\end{document}

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.