Here is my comment as an answer because I cannot comment and was searching for this solution for hours.
@Eagle asked:
@Jake, I tried this solution where instead of defining \newcommand{\plotfile}[1], I simply apply it below \begin{axis} and it didn't work. I am interesting to know why... What is the reason?
When using the
\pgfplotsinvokeforeach{1,...,\numberofcols}{}
not within a function, a single # needs to be used as index.
\documentclass{article}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents}{testdata.dat}
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
\end{filecontents}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=north west]
\pgfplotstableread{testdata.dat}{\table}
\pgfplotstablegetcolsof{\table}
\pgfmathtruncatemacro\numberofcols{\pgfplotsretval-1}
\pgfplotsinvokeforeach{1,...,\numberofcols}{
\pgfplotstablegetcolumnnamebyindex{#1}\of{\table}\to{\colname}
\addplot table [y index=#1] {\table};
\addlegendentryexpanded{\colname}
}
\end{axis}
\end{tikzpicture}
\end{document}
\newcommand{\plotfile}[1], i simply apply it below\begin{axis}and it didn't work. I am interesting to know why... What is the reason? – Eagle Feb 16 '12 at 09:55