2

In Change color in addplot in for loop of pgfplots It was discussed how to loop over nonexistent colours in \addplot and axis I would however like to loop over existing colours, but:

\documentclass[border=5pt,tikz]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usepackage{graphicx}
\usepackage{xcolor}
\definecolor{greyscale1}{rgb}{0.1,0.1,0.1}

\begin{document} \begin{tikzpicture} \begin{axis} \foreach \file in {1} \addplot[color=greyscale\file] table [col sep=comma] {d.dat};; \end{axis} \end{tikzpicture} \end{document}

returns the error:

Package xcolor Error: Undefined color `greyscale\file '.

If instead I do:

\documentclass[border=5pt,tikz]{standalone}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usepackage{graphicx}
\usepackage{xcolor}
\definecolor{greyscale1}{rgb}{0.1,0.1,0.1}

\begin{document} \begin{tikzpicture} \foreach \file in {1} \draw[color=greyscale\file] (0,2) -- (1,2); \end{tikzpicture} \end{document}

I get:

enter image description here

Edit:

d.dat looks like

0,2
1,2

1 Answers1

1

These are the usual expansion issues. One way to go here is to use \pgfplotsinvokeforeach.

\documentclass[border=5pt,tikz]{standalone}
\usepackage{filecontents}
\begin{filecontents*}{d.dat}
0,2
1,2
\end{filecontents*}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usepackage{graphicx}
\usepackage{xcolor}
\definecolor{greyscale1}{rgb}{0.1,0.1,0.1}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[ymin=1.8,ymax=2.2]
    \pgfplotsinvokeforeach{1}
    {\addplot[color={greyscale#1}] table [col sep=comma] {d.dat};}
  \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

  • Yup, I found out ;-) While this works for having to loop over 1 variable the answer: https://tex.stackexchange.com/a/170670/125223 is needed to loop over more. Unless you can do something cool with \pgfplotsinvokeforeach – Thorbjørn E. K. Christensen Oct 02 '18 at 11:57
  • @ThorbjørnE.K.Christensen The answer in your link also has just one argument, but if you want several, look at this answer by the author of pgfplots. These expansion issues are not limited to \foreach, i.e. there are several other situations in which you may want to do \edef\temp{\noexpand\addplot ...} \temp but here you do not need it. –  Oct 02 '18 at 12:01