1

I'd like to use \pgfplotsinvokeforeach with a parameter to draw different plots with different colors.

What I tried is \pgfmathsetmacro but this does not work (see example, the value is fixed at 100).

Does anybody know the reason for this? And is it possible to define a parameter inside the \pgfplotsinvokeforeach-environment?

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{tikz} 

\begin{document}
\begin{tikzpicture}[scale=1,>=latex,font= \footnotesize]
\begin{axis}[axis lines = middle,xlabel = $x$,ylabel = {$y$},samples=100,domain=-0.9:4.2,grid=both,minor tick num=1]
\pgfplotsinvokeforeach{-2,0,2,4,6}{
\pgfmathsetmacro{\m}{(#1+2)/8*100};
\addplot[blue!\m!red] {(3-#1)/4*x^2+(#1-2)*x+1} node[pos=.55,above] {$u=#1 (\m)$};
\draw[blue!\m!red] (axis cs:{2,#1}) circle (2pt);}
\draw (axis cs:{0,1}) circle (2pt);
\draw (axis cs:{4,5}) circle (2pt);
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

1

The problem is that the \addplot commands are accumulated in the loop, with \m still unexpanded. When the plots are finally drawn, the current value of \m is used, which is its last one, 100.0.

You can put the loop body into a macro:

\newcommand\myplot[2]{%#1 = color mix, #2 = plot parameter
  \addplot[blue!#1!red] {(3-#2)/4*x^2+(#2-2)*x+1} node[pos=.55,above] {$u=#2 (#1)$};
  \draw[blue!#1!red] (axis cs:{2,#2}) circle (2pt);
}

and make sure that all of its arguments get expanded before calling it:

\expandafter\myplot\expandafter{\m}{#1}

The order of arguments is not arbitrary: with the \expandafter commands I can reach only into the first argument, so the first argument has to be \m and the second one is the loop value.

enter image description here

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\newcommand\myplot[2]{%
  \addplot[blue!#1!red] {(3-#2)/4*x^2+(#2-2)*x+1} node[pos=.55,above] {$u=#2 (#1)$};
  \draw[blue!#1!red] (axis cs:{2,#2}) circle (2pt);
}
\begin{tikzpicture}[scale=1,>=latex,font= \footnotesize]
\begin{axis}[axis lines = middle,xlabel = $x$,ylabel = {$y$},samples=100,domain=-0.9:4.2,grid=both,minor tick num=1]
\pgfplotsinvokeforeach{-2,0,2,4,6}{
  \pgfmathsetmacro{\m}{(#1+2)/8*100};
  \expandafter\myplot\expandafter{\m}{#1}
}
\draw (axis cs:{0,1}) circle (2pt);
\draw (axis cs:{4,5}) circle (2pt);
\end{axis}
\end{tikzpicture}
\end{document}

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.