I have large number of files of data which I want to plot using gnuplot. The files are in text form, in the form of multiple columns. I wanted to use gnuplot to plot all columns in a given file, without the need for having to identify the number of the columns to be plotted or even then total number of columns in the file, since the total number of columns tend to vary between the files I am having. Is there some way I could do this using gnuplot?
Asked
Active
Viewed 6,656 times
2 Answers
12
There are different ways you can go about this, some more and some less elegant.
Take the following file data
as an example:
1 2 3
2 4 5
3 1 3
4 5 2
5 9 5
6 4 2
This has 3 columns, but you want to write a general script without the assumption of any particular number. The way I would go about it would be to use awk
to get the number of columns in your file within the gnuplot script by a system()
call:
N = system("awk 'NR==1{print NF}' data")
plot for [i=1:N] "data" u 0:i w l title "Column ".i
Say that you don't want to use a system()
call and know that the number of columns will always be below a certain maximum, for instance 10:
plot for [i=1:10] "data" u 0:i w l title "Column ".i
Then gnuplot will complain about non-existent data but will plot columns 1 to 3 nonetheless.

Miguel
- 7,497
- 2
- 27
- 46
-
5Recent versions of Gnuplot have the `stats` command, so if you run `stats 'data' nooutput` the `STATS_columns` variable will contain the number of columns, 3 in this case. – Thor Mar 17 '15 at 00:10
-
1@Thor `STATS_columns` is available since 5.0 – Christoph Mar 17 '15 at 07:14
-
@Christoph Thanks for the clarification, actually running `stats` was the first thing I did before posting the answer, and I didn't see anything pertaining to column number (I run 4.6.4). – Miguel Mar 17 '15 at 09:18
-
I thought so. After Thor's comment I also had to look when this was introduced. Gnuplot 5 can also extract matrix dimensions from a data file. – Christoph Mar 17 '15 at 11:20
3
Now you can use "*" symbol:
plot for [i=1:*] 'data' using 0:i with lines title 'Column '.i

Александр Меняйло
- 41
- 3
-
1yes, as far as I can tell it is documented from gnuplot 5.0.3 on (Feb 2016). Check `help for loops`. – theozh May 23 '22 at 14:30