7

I have a file with several columns of data (the number of columns N might me quite large). I want to plot all the columns as a function of the first one (that is, plot 'Data.txt' using 1:2, 'Data.txt' using 1:3, ..., 'Data.txt' using 1:N). The thing is, I want this command to work when I don't know the number of columns. Is that possible?

Valentine
  • 107
  • 2
  • 7

4 Answers4

10

You can count the number of columns in your file using awk and then do a looped plot. There might be a function to get the number of columns in your data file already implemented in gnuplot but I do not know it. You can try this:

N=`awk 'NR==1 {print NF}' Data.txt`
plot for [i=2:N] "Data.txt" u 1:i

If your first row contains a comment (starting by #) change NR== to the appropriate value. If you have a variable number of columns for different rows then you might want to complicate the awk command.

Miguel
  • 7,497
  • 2
  • 27
  • 46
3

@Paul shows a correct answer, but an even simpler variant is possible. You can use an open-ended iteration that stops when it runs out of columns:

plot for [n=1:*] "data.dat" using 1:n title sprintf("Column %d",n)
Ethan
  • 13,715
  • 2
  • 12
  • 21
2

Seeing that this questions is very old, I still think it is worth revisiting, as you now (Version 5.2) have access to the number of columns in a file without relying on external tools.

DATA = 'path/to/datafile.txt'
stats DATA

will (among other stuff) store the number of columns in the variable STATS_columns, so now you can do something like:

N=STATS_columns
plot for [i=2:N] DATA using 1:i title DATA.' '.i with lines

which will plot all the columns (assuming the first column is used for the x-axis) with legend entries matching the filename plus the column number.

PS: Not sure when this feature was introduced, but it's there now. :)

Paul
  • 165
  • 6
1

You will need two script files:

==== main.plt ====
set <whatever>
N=1
load "loop.plt"

==== loop.plt ====
replot "data.dat" u 0:(column(N))
N+=N+1
if(N<4) reread

Function reread cause that the next line to read by gp will be loop.plt:1. Now you will plot first three columns of data.dat. Function replot adds plot to current image.

Or see: how to convert integer to string in gnuplot?.

Community
  • 1
  • 1
Luuuucky
  • 139
  • 1
  • 10