Plot multiple datasets from one file

gnuplot

Note: I can control the format of the data file, but it has to be a single file.

I'm trying to plot multiple datasets on the same graph using gnuplot. I'd like ideally to plot something like this:

data_1 0 0
data_2 0 0
data_1 1 1
data_2 0 1
data_1 2 2
data_2 1 2

And so on. In this case, data_1 and data_2 should be two separate curves.

I'd also like to avoid putting in the gnuplot script the list, or even the number, of possible datasets. Basically, I'd like it to "group" data points by a specific field, and plot each group as a separate dataset on the same graph.

As a last-resort alternative, I could split the original file into one file per dataset using grep, and plot those (I guess it's easier?), but I'm looking for a way to do it with a single file.

Best Answer

The gnuplot-way to save your data would be to separate the data sets with two empty lines. Then you can use index to access the different data sets in the single file:

data_1 0 0
data_1 1 1
data_1 2 2


data_2 0 0
data_2 0 1
data_2 1 2

And plot that with

plot 'file.dat' using 2:3 index 0, '' using 2:3 index 1

To get the number of data sets, use the stats command which saves the number of data sets (data blocks) in a variable which you can use for iterating:

stats 'file.dat' using 0 nooutput
plot for [i=0:(STATS_blocks - 1)] 'file.dat' using 2:3 index i

To extend this, you could even format your file as follows

data_1
0 0
1 1
2 2


data_2
0 0
0 1
1 2

and use the first line of seach data set as plot key:

set key autotitle columnheader
stats 'file.dat' using 0 nooutput
plot for [i=0:(STATS_blocks - 1)] 'file.dat' using 1:2 index i

enter image description here

Related Topic