Ron
Ron

Reputation: 177

Gnuplot: several plots from single file where the data are interspersed

I have a single file from where I want to draw 2 plots in the same graph. I know how to do it if the data for 2 plots are separated, but how do I do it when the data for each plot are interspersed with others?

Example, here is the data file, the first column represents which plot the data belongs to, the 2nd and 3rd column are x axis and y axis values:

# plotnum xaxis yaxis
1 2 1
2 3 2
1 3 2
2 5 4

From here I would like to draw 2 plots, plot1 and plot2, and first plot plots (2,1) and (3,2) where the second plot plots (3,2) and (5,4)

How do I achieve that?

Upvotes: 0

Views: 262

Answers (2)

theozh
theozh

Reputation: 25684

Just for the records, there is no need to use gawk or other external tools, you can simply do it with gnuplot only and hence platform-independently.

For gnuplot<5.0.7 you have to use a workaround for connecting the filtered data points with lines.

Script: (works for gnuplot>=5.0.7, Aug 2017)

### filter data
reset session

$Data  <<EOD
# plotnum xaxis yaxis
1 2 1
2 3 2
1 3 3
2 5 4
1 4 4
2 6 2
EOD

set datafile missing NaN
myFilter(colD,colF,valF) = column(colF) == valF ? column(colD) : NaN

plot for [i=1:2] $Data u (myFilter(2,1,i)):3 w lp pt 7 ti sprintf("Dataset %d",i)
### end of script

Result:

enter image description here

Addition:

The above script checks if the first column is 1 or 2, which is the general case and covers arbitrary sequences of 1 and 2. However, if you can be sure that column 1 starts with 1 and is strictly alternating with 2, then you can do the following which actually uses every and is much simpler.

Data: SO39154659.dat

# plotnum xaxis yaxis
1 2 1
2 3 2
1 3 3
2 5 4
1 4 4
2 6 2

Script: (works at least with gnuplot>=4.4.0, March 2010)

### plot alternating data
reset

FILE = "SO39154659.dat"

plot for [i=1:2] FILE u 2:3 every 2::i-1 w lp pt 7 ti sprintf("Dataset %d",i)
### end of script

Result: (same as graph above)

Upvotes: 0

ewcz
ewcz

Reputation: 13087

you can use the every keyword like this:

plot 'test.dat' every ::0::1 using 2:3 w lp, '' every ::2::3 using 2:3 w lp

For example ::0::1 instructs Gnuplot to select points 0 through 1, i.e., the first two (the "point index" is zero-based)

EDIT: in case the first column should determine which plot the remaining two columns belong to, one solution is to rely on external utilities such as gawk in order to pre-filter the file:

filter(fname, group)=sprintf("<gawk '$1==%d{print $2,$3}' %s", group, fname)
plot filter('test.dat', 1) w l

Here, gawk already also filters out only the second and third columns so that one does not need to use the using keyword later.

Upvotes: 1

Related Questions