pgfplotstable: How to access column name?
As @percusse stated correctly, the root challenge here is that these columns/<name>/.style
things are only interpreted in the context of \pgfplotstabletypeset
.
A solution which is also a direct answer to your question and solves the MWE means to query the information from the correct context. This is simpler than it sounds and I can give such an example below. It does not need ANY knowledge of internals of pgfplotstable
. It only relies on pgfkeys
and basic TeX expansion control.
Here is the solution:
\documentclass{article}
\usepackage{amsmath}
\usepackage{pgfplots, pgfplotstable, filecontents}
\pgfplotsset{compat=1.6}
\begin{filecontents}{test.dat}
Time Distance
0 0
1 1
3 2
\end{filecontents}
\pgfplotstableset{
columns/Time/.style={
column name={$t_{\alpha}$},
},
columns/Distance/.style={
column name={$D_{\alpha}$},
},
}
% defines \devendraretval to contain the display name for the column
% named '#1'
%
% #1: a column name
\def\getcolumndisplayname#1{%
% we WANT a group. Otherwise, any values set in these style would
% become global and they would be mixed up between different
% columns.
\begingroup
% Access the contents of column's display name programmatrically:
\pgfplotstableset{columns/#1/.try}%
\pgfkeysgetvalue{/pgfplots/table/column name}\temp
\ifx\temp\empty
% oh. We have no such value! Ok, use the column name as
% such.
\edef\temp{#1}%
\fi
% this here is one of the possible patterns to communicate a
% local variable outside of a local group:
\global\let\GLOBALTEMP=\temp
\endgroup
\let\devendraretval=\GLOBALTEMP
%
}%
\begin{document}
\thispagestyle{empty}
\pgfplotstableread{test.dat}\loadedtable
\pgfplotstabletypeset{\loadedtable}
\pgfplotstableforeachcolumn\loadedtable\as\col{%
%
\getcolumndisplayname{\col}%
column name is ‘\col’; index is \pgfplotstablecol; display name is `\devendraretval'\par
}
\getcolumndisplayname{Time}%
Value of Time is \devendraretval.
\end{document}
It defines a new command `\getcolumndisplayname{}' which retrieves it.
Please refer to http://pgfplots.sourceforge.net/TeX-programming-notes.pdf for details about the basic instructions.
Alternative from my comment (and from Use first row of a table as legend entry in pgfplot graph?):
\documentclass[border=1pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.6}
\pgfplotstableread{
time distance velocity something
0 0 1 0.2
1 1 1 0.3
1.999 1.999 1 0.4
2 2 0 0.4
3 2 0 0.5
}\mytable
\pgfplotstableread{
name alias
time $t$
distance $d_\alpha$
velocity $\sin(2t)$
something nothing
}\tablenames
\pgfplotstablegetcolsof{\mytable}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\pgfplotsinvokeforeach{1,...,\numberofcols}{
\addplot table [y index=#1] \mytable;
\pgfplotstablegetelem{#1}{[index] 1}\of{\tablenames}
\addlegendentryexpanded{\pgfplotsretval}
}
\end{axis}
\end{tikzpicture}
\end{document}