7

From reading Tikz and PGFPlots manuals I got an impression that using multiple loop variables syntax in \foreach I should be able to change color of the plots using \clr loop variable in \addplot parameters:

\documentclass{article}
\usepackage{tikz,pgfplots}

\begin{document}

    \begin{tikzpicture}[font=\tiny]
        \begin{axis}[
            axis x line=center,
            axis y line=center,
            restrict y to domain=-100:100,
        ]
        \foreach \d/\clr in {1/orange, 2/red, 3/green, 4/blue, 5/brown}
        {
            \addplot[smooth,\clr,domain=-5:5]{(x-\d)^3};
        }
        \end{axis}
    \end{tikzpicture}

\end{document}

That did not work. What am I missing?

ajeh
  • 2,572
  • \clr is not expanded. you need to either use \pgfplotsinvokeforeach for single variable or define your own cycle list. Or – percusse Aug 16 '16 at 22:12

1 Answers1

6

This is an expansion issue (and I not the right person to attempt to explain it). But, a way to get the desired results is to use \pgfplotsinvokeforeach which expands the contents of its body. I used xstring to parse the two components, but other techniques can be used as well.

enter image description here

Notes:

  • When using short macro names it is best to make sure you are not overwriting existing commands, thus the \newcommands. This technique would have shown that \d is an existing macro.

Code:

\documentclass[border=2pt]{standalone}
\usepackage{tikz,pgfplots}
\usepackage{xcolor}
\usepackage{xstring}
\pgfplotsset{compat=newest}

\newcommand{\diff}{}% Ensure it is not already defined \newcommand{\clr}{}% Ensure it is not already defined

\begin{document}

\begin{tikzpicture}[font=\tiny]
    \begin{axis}[
        axis x line=center,
        axis y line=center,
        restrict y to domain=-100:100,
    ]
    \pgfplotsinvokeforeach{1/orange, 2/red, 3/green, 4/blue, 5/brown}
    {
        \StrBefore{#1}{/}[\diff]%
        \StrBehind{#1}{/}[\clr]%
        \edef\AddPlot{\noexpand\addplot[thick,smooth,color=\clr,domain=-5:5] {(x-\diff)^3};}%
        \AddPlot
    }
    \end{axis}
\end{tikzpicture}

\end{document}

Peter Grill
  • 223,288