TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using pgfplots extensively and I'd like to avoid having to write legends every time, since all the text files I want to plot have explicit headers.

As a comparison, \pgfplotstabletypeset makes a nice table instantly with my data, and I'm looking for a similar way to get graphs in an easier way than having to specify each column, legend, etc....

share|improve this question
up vote 20 down vote accepted

You can access the column names of a PGFplots table through the macro \pgfplotstablegetcolumnnamebyindex{<index>}\of{<table macro>}\to{<macro>}. You can use this while looping through the columns of a table using \pgfplotsinvokeforeach{<list>}{<commands>} to add the column names as legend entries.

I've written a \plotfile macro that takes a filename as argument and then plots all columns starting from the second column against the first column:


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

        \addplot table [y index=##1] {testdata.dat}; 

\begin{axis}[legend pos=north west]

plotting columns from a table

share|improve this answer
awesome thanks a lot. – ben paillard Jul 27 '11 at 22:25
@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? – Eagle Feb 16 '12 at 9:55

I used the following to read a file, plot some columns and add legend entries, this worked fine:

width=\columnwidth, height=0.7\columnwidth,
xlabel={Frequency (GHz)}, ylabel={Image rejection (dB)}]
\foreach \n in {3,4,...,6} {
  \addplot table[x=IF,y index=\n]{\SimIR};
\caption{Image rejection versus frequency.}%
share|improve this answer
If I understand correctly, the main differences between this and my answer are the use of \foreach instead of \pgfplotsforeachungrouped and the hard-coding of the columns to be plotted? – Jake Jan 25 '14 at 15:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.