2

I have a CSV file which contains different sets of plot-data (x1,y1,z1), ..., (xn,yn,zn) and some additional data, one of which I would use as legend.

My current code is as follows:

\documentclass{article}

\usepackage{pgfplotstable,pgfplots,tikz}

\pgfplotstableread[col sep=comma,display columns/setting/.style=string type]{
x0,y0,z0,x1,y1,z1,plotID,setting
-1,2,0.149858,-1,6,0.582841,1,asdasd
-1,8,0.447147,-1,9,0.548643,2,test
}\table

\begin{document}
    \begin{tikzpicture}
        \begin{axis}
            \pgfplotstablegetcolsof\table
            \pgfmathsetmacro{\plots}{(\pgfplotsretval-2)/3-1}
            \pgfplotsinvokeforeach{0,...,\plots} {
                \addplot table[x=x#1,y=z#1] {\table};
                \pgfplotstablegetelem{#1}{setting}\of{\table}
                %\edef\bla{\pgfplotsretval}
                %\def\bla{\pgfplotsretval}
                \xdef\bla{\pgfplotsretval}
                \addlegendentry{\bla};
            }
        \end{axis}
    \end{tikzpicture}
\end{document}

The plotting seems to work fine, howver, adding the legend makes some troubles. Depending on whether I use \def, \edef \xdef or directly \pgfplotsretval for \addlegendentry, I get either nothing or just test as legend. However, it should show asdasd for the first plot and test for the second only.

What is the right way of doing it?

2

Since Hubble's discovery, we know that the universe is expanding, and so does pgfplots. Here comes a standard trick to deal with this:

\edef\temp{\noexpand\addlegendentry{\pgfplotsretval};}
\temp

means that in \temp \addlegendentry is not yet expanded, but \pgfplotsretval is. So when the loop is run through for the first time, \temp will be \addlegendentry{asdasd}. Calling \temp now will set the appropriate legend entry.

\documentclass{article}

\usepackage{pgfplotstable,pgfplots,tikz}

\pgfplotstableread[col sep=comma,display columns/setting/.style=string type]{
x0,y0,z0,x1,y1,z1,plotID,setting
-1,2,0.149858,-1,6,0.582841,1,asdasd
-1,8,0.447147,-1,9,0.548643,2,test
}\table

\begin{document}
    \begin{tikzpicture}
        \begin{axis}
            \pgfplotstablegetcolsof\table
            \pgfmathsetmacro{\plots}{(\pgfplotsretval-2)/3-1}
            \pgfplotsinvokeforeach{0,...,\plots} {
                \addplot table[x=x#1,y=z#1] {\table};
                \pgfplotstablegetelem{#1}{setting}\of{\table}
                \edef\temp{\noexpand\addlegendentry{\pgfplotsretval};}
                \temp
            }
        \end{axis}
    \end{tikzpicture}
\end{document}

enter image description here

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.