3

My question is related to this one, \foreach not behaving in axis environment , but the solution there does not work in my case and unlike the related question, the loop works well in the axis environment until we try to pass the parameter color=\c.

Also, if I remove the plot from outside the axis environment and plot in TikZ, it works fine (so the foreach syntax is OK) but then I can not fit the picture properly to its axis (see second source code example).

Here is the MWE (addplot and plot generate the same error):

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
 \begin{document}
 \begin{tikzpicture}[
 declare function={ kL(\x,\n)=5/max(5,6*\x*\n+\n-\n*\x);}]
 \begin{axis}[
 title=Test,
 xlabel=$\frac{\alpha_L}{\alpha_H}$,
 ylabel=$\kappa_{L}$]
 \foreach \n/\c in {0/black,1/green,2/red,3/blue}
  {\plot[color=\c,
  domain=0.1:1,
  samples=50,
   ]{kL(\x,\n)};
   } 
   \end{axis}
   \end{tikzpicture}
   \end{document}

Here is what happens if you take it outside the axis environment and write it in TikZ:

\documentclass[12pt]{article}
 \usepackage{tikz}
 \usepackage{pgfplots}
 \pgfplotsset{compat=1.10}
 \begin{document
 \begin{tikzpicture}[
 declare function={kL(\x,\n)=5/max(5,6*\x*\n+\n-\n*\x);
 \begin{axis}[
 title= Test II,
 xlabel=$\frac{\alpha_L}{\alpha_H}$,
 ylabel=$\kappa_{L}$]
 \end{axis}
 \foreach \n/\d in {0/black,1/green,2/red,3/blue}
 \draw [color=\d,
 domain=0.1:1,
samples=50,
 ]  plot (\x,{kL(\x,\n)});
 \end{tikzpicture}
 \end{document}
5

This is typical when the variables are not expanded in a timely fashion, you can enforce it artificially. Because pgfplots first harvests the plots and then draws all of them at once. You need to provide the expanded version otherwise later the variables won't have the meaning as they have within the loop. Hence the \c is considered as the text cedilla command instead of the color variable.

\documentclass[12pt]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\begin{document}
 \begin{tikzpicture}[
 declare function={ kL(\x,\n)=5/max(5,6*\x*\n+\n-\n*\x);}]
 \begin{axis}[
 title=Test,
 xlabel=$\frac{\alpha_L}{\alpha_H}$,
 ylabel=$\kappa_{L}$]
 \foreach \n/\c in {0/black,1/green,2/red,3/blue}
  {\edef\temp{\noexpand\addplot[color=\c,
  domain=0.1:1,
  samples=50,
   ]{kL(\noexpand\x,\n)};}\temp
   } 
   \end{axis}
   \end{tikzpicture}
   \end{document}

enter image description here

  • Thanks! I just discover cycle list and that solves the problem but I love the answer because we learn more about TeX expansion. – Sergio Parreiras Jun 27 '14 at 21:55

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.