gnuplot reading data to an array or referencing point coordinates in an external file

Viewed 41

Is there a way in gnuplot to loop through data points in a data file? Let's say I have a file with the data

# x y 
1 2
2 5
3 1
4 5
5 6 

And I am looking how to draw lines in a loop from some x, y to some other x, y from the files. Something like:

j=0
x3 = data[1][1]
y3 = data[1][2]
do for [i=1:4] {
  x1 = data[i][1]
  y1 = data[i][2]
  x2 = data[i+1][1]
  y2 = data[i+1][2]
  j=j+1
  set arrow j from first x3,y3 to first x2,y1
  j = j+1
  set arrow j from first x2,y1, to first x2, y2
  x3 = x2
  y3 = y2
}

where data would be some array or matrix representation of data file. I think I could live with the ability to read the datafile into, say, 4 separate arrays. But i have not found anything even close to this.

Note that vector plotting is probably not general enough to cover this case.

1 Answers

If I interpreted your intention correctly, you want to plot a stepwise function. There is a gnuplot plotting style with steps (check help steps). However, if you want arrows it's probably getting a bit more complicated and you have to use the style with vectors or with arrows, check help vectors and help arrows.

Script:

### plotting steps with and without arrowheads
reset session

$Data <<EOD
# x y
 1   2
 2   5
 3   1
 4   5
 5   6
EOD

set offsets 1,1,1,1
set key noautotitle

set multiplot layout 2,1

    plot $Data u 1:2 w steps lw 2 lc "web-green"

    plot x1=y1=NaN $Data u (x0=x1,x1=$1,x0):(y0=y1,y1=$2,y0):(x1-x0):(0) \
         w vec     head lw 2 lc "red", \
         x1=y1=NaN    '' u (x0=x1,x1=$1):(y0=y1,y1=$2):      (0):    (y0-y1) \
         w vec backhead lw 2 lc "red"

unset multiplot
### end of script

Result:

enter image description here

Related