# foreach with colors leads to “undefined control sequence”

The following MWE works nicely when I remove the optional argument [\forcol] from the \addplotcommand or when I change it to red, for example. Though I would like the curves to have different colors as defined in my list {1/black,2/red,3/green,4/blue,5/orange}, so I tried it as the following, but then it throws me the error

"! Undefined control sequence. \end{axis}"

\documentclass{article}
\usepackage{xcolor}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\foreach \foridx/\forcol in {1/black,2/red,3/green,4/blue,5/orange}{
}
\end{axis}
\end{tikzpicture}
\end{document}


What is my mistake? I would like to have this feature to set up a command for plotting many data files.

• referencing section 8 of the manual, you can use \pgfplotsforeachungrouped \foridx/\forcol in {1/black,2/red,3/green,4/blue,5/orange}{ \addplot[\forcol]{x^\foridx}; \edef\temp{\noexpand\addplot[\forcol]{x^\foridx};} \temp } – cmhughes Mar 28 '16 at 14:29
• @cmhughes: great, this works, thanks! You can create an answer of this! But I don't really understand this "magic" (even with the description of the manual), what the "extra groups" are that are not introduced here. – riddleculous Mar 28 '16 at 14:37
• @cmhughes: I just realize you had the  \addplot[\forcol]{x^\foridx}; also outside your temp environment. This should be omitted. – riddleculous Mar 28 '16 at 17:11

You can try some \expandafter... statements to expand the \foreach loops. \foreach loops can be quite tricky, in my point of view, due to the way the \forcol macros are defined by pgffor.

\documentclass{article}
\usepackage{xcolor}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\pgfplotsforeachungrouped \foridx/\forcol in {1/black,2/red,3/green,4/blue,5/orange}{

• i simply removed [\forcol] and the plot showed. but it has a lot of points in it. – naphaneal Mar 28 '16 at 14:40
• @riddleculous: It can be really complicated with \expandafters, in my point of view, in nested \foreach loops and multiple \addplot[\foo,\forbar,\morefoo]{...} – user31729 Mar 28 '16 at 14:53
• Your and cmhughes code are not the same. You are both expanding the color command (which is needed), but cmhughes also avoid the grouping around the \addplots. I would suggest to use \pgfplotsforeachungrouped in your code too. – Ulrike Fischer Mar 28 '16 at 14:53
• @UlrikeFischer: Thanks, I've replaced \pgfplotsforeachungrouped instead of the usual \foreach – user31729 Mar 28 '16 at 15:00