[Tex/LaTex] How to create pgfplots cycle list from a table

pgfplotspgfplotstable

I know that a pgfplots cycle list can be created with \pgfplotscreateplotcyclelist. However, the examples given in the pgfplots manual explicitly list all the items. I am wondering if it is possible to create a cycle list by looping through a table (potentially loaded from a file). This is very useful when there are large number of \addplot and each needs a special style. Any idea how to do this? Thanks.

Best Answer

The reason why Jake's solution doesn't work is that the \listmacro isn't expanded before the pgfplotscreateplotcyclelist macro searches for the \\ separators. Therefore the whole macro is taken as one setting and the included \\ are expanded as part of the setting which causes an error (line breaks in settings don't make much sense).

So in order to make it work you have to manually expand \listmacro first and than feed it to \pgfplotscreateplotcyclelist. There are multiple ways to do this. Here a way which uses eTeX's \unexpanded inside \edef to expand the \listmacro only once, otherwise the \\ are expanded to early and cause also errors. I defined a new macro \pgfplotscreateplotcyclelistfrommacro which expands the second argument and then calls \pgfplotscreateplotcyclelist. Feel free to rename it.

Based on Jake's code:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\newcommand*{\pgfplotscreateplotcyclelistfrommacro}[2]{%
    \begingroup
    % Expands the second argument once. The `\A` is only temporary used
    % and therefore in a group
    \edef\A{\noexpand\pgfplotscreateplotcyclelist{#1}{\unexpanded\expandafter{#2}}}%
    \expandafter
    \endgroup\A
}

\begin{filecontents}{cyclelist.txt}
green
pink
purple
\end{filecontents}
\pgfplotstableread{cyclelist.txt}{\cyclelist}

\begin{document}

\pgfplotstabletypeset[begin table={},end table={},skip coltypes,display columns/0/.style={string type},write to macro=\listmacro,typeset=false]\cyclelist

\begin{tikzpicture}
\pgfplotscreateplotcyclelistfrommacro{newcycle}{\listmacro}
\begin{axis}[cycle list name=newcycle]
\addplot {x^2};
\addplot {x^4};
\addplot {x^6};
\end{axis}
\end{tikzpicture}

\end{document}
Related Question