indexinggnuplotarrows

How to connect points with different indices (one data file) in gnuplot


I have a file "a_test.dat" with two data blocks that I can select via the corresponding index.

# first
x1  y1
3   1
6   2
9   8

# second
x2  y2
4   5
8   2
2   7

Now I want to connect the data points of both indices with an arrow.

set arrow from (x1,y1) to (x2,y2).

I can plot both blocks with one plot statement. But I cannot get the points to set the arrows.

plot "a_test.dat" index "first" u 1:2, "" index "second" u 1:2


Solution

  • From version 5.2 you can use gnuplot arrays:

    stats "a_test.dat" nooutput
    array xx[STATS_records]
    array yy[STATS_records]
    # save all data into two arrays
    i = 1
    fnset(x,y) = (xx[i]=x, yy[i]=y, i=i+1)
    # parse data ignoring output
    set table $dummy
    plot "" using (fnset($1,$2)) with table
    unset table
    # x2,y2 data starts at midpoint in array
    numi = int((i-1)/2)
    
    plot for [i=1:numi] $dummy using (xx[i]):(yy[i]):(xx[numi+i]-xx[i]):(yy[numi+i]-yy[i]) with vectors
    

    Use stats to count the number of lines in the file, so that the array can be large enough. Create an array xx and another yy to hold the data. Use plot ... with table to read the file again, calling your function fnset() for each data line with the x and y column values. The function saves them at the current index i, which it increments. It was initialised to 1.

    For 3+3 data lines, i ends up at 7, so we set numi to (i-1)/2 i.e. 3. Use plot for ... vectors to draw the arrows. Each arrow needs 4 data items from the array. Note that the second x,y must be a relative delta, not an absolute position.

    enter image description here