2

I would like my code to use the column name (from pgfplotstable) to automatically label the lines.

Here is a MWE:

\documentclass{standalone}

\usepackage{pgfplots}
\pgfplotsset{compat=1.13}    

\usepackage{filecontents}
\begin{filecontents}{data.txt}
T   1e5 2e5 3e5 4e5
100 1   1.5 2   2.5
200 2   2.5 3   3.5
300 3   3.5 4   4.5
400 4   4.5 5   5.5
\end{filecontents}

\pgfplotstableread{data.txt}{\DATA}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[ylabel={T},
    xlabel={Values}]
    \pgfplotsforeachungrouped \i in {1,2,...,4} {
        \pgfplotstablegetcolumnnamebyindex{\i}\of{\DATA}\to{\colname}
        \addplot+ table [x index=\i, y={T}] {\DATA} node [pos = 0.85, sloped, fill = white] {P = \colname};
    }
    \end{axis}
\end{tikzpicture}

\end{document}

MWE

Here the indicated pressure is always the same, but I would like to take it from the column name of the table.

Same result with

\pgfplotsinvokeforeach {1,2,...,4} {
    \pgfplotstablegetcolumnnamebyindex{#1}\of{\DATA}\to{\colname}
    \addplot+ table [x index=#1, y={T}] {\DATA} node [pos = 0.85, sloped, fill = white] {P = \colname};
}
1

According to my understanding (please correct me if I am wrong), all plot commands are evaluated in \end{axis}. Therefore, the value of \colname is the value of the last column (4e5 in this case). In order to get the correct value, it must be evaluated in each loop. Follow the discussion in the pgfplots manual, section 8.1 about the command \pgfplotsforeachungrouped, I use \edef to get \colname evaluated. Note the use of \noexpand right before \addplot and \DATA. \edef will removes these \noexpand to give the following sequences of characters \addplot and \DATA. Since there is not a \noexpand right before \colname, it will be evaluated by \edef.

enter image description here

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.13}    

\usepackage{filecontents}
\begin{filecontents}{data.txt}
T   1e5 2e5 3e5 4e5
100 1   1.5 2   2.5
200 2   2.5 3   3.5
300 3   3.5 4   4.5
400 4   4.5 5   5.5
\end{filecontents}


\begin{document}

\begin{tikzpicture}
    \begin{axis}[ylabel={T},
    xlabel={Values}]
\pgfplotstableread{data.txt}{\DATA}
\pgfplotstablegetcolsof{\DATA}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
   \pgfplotsinvokeforeach{1,...,\numberofcols}{
        \pgfplotstablegetcolumnnamebyindex{#1}\of{\DATA}to{\colname}
        \edef\letsdraw{\noexpand\addplot table [x index=#1, y={T}]
        {\noexpand\DATA} node [pos = 0.85, sloped, fill = white]
        {P=\colname};}
        \letsdraw
    }
    \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.