'Gnuplot: store last data point as variable

I was wondering if there is an easy way, using Gnuplot, to get the last point in a data file say data.txt and store the values in a variable.

From this question, accessing the nth datapoint in a datafile using gnuplot I know that I can get the X-Value using stats and GP_VAL_DATA_X_MAX variable, but is there a simple trick to get the corresponding y-value?



Solution 1:[1]

If you want to use Gnuplot, you can

plot 'data.txt'
plot[GPVAL_DATA_X_MAX:] 'data.txt'
show variable GPVAL_DATA_Y_MAX

OR

plot 'data.txt'
plot[GPVAL_DATA_X_MAX:] 'data.txt'
print GPVAL_DATA_Y_MAX

Solution 2:[2]

A third possibility is to write each ordinate value into the same user variable during plotting. Last value stays in:

 plot dataf using 1:(lasty=$2)
 print lasty

Solution 3:[3]

If you know how your file is organised (separators, trailing empty lines) and you have access to standard Unix tools, you make use of Gnuplot’s system command. For example, if you have no trailing newlines and your values are separated by tabs, you can do the following:

x = system("tail -n 1 data.txt | cut -f 1")
y = system("tail -n 1 data.txt | cut -f 2")

(tail gets the last n lines of a file. cut extracts the column f.)

Note that x and y are strings if obtained this way, but for most applications this should not matter. If you must convert them, you can still add zero.

Solution 4:[4]

Let me add a 4th solution, because:

  • To be very precise, the OP asked about the last x-value and the correscponding y-value. @TomSolid's solution will return the maximum x-value and its corresponding y-value. However, strictly speaking the maximum value might not necessarily be the last value, unless the x-data is sorted in ascending order. The result for the example below would be 10 and 14 instead of 8 and 18.

  • @Karl's solution will return the last y-value and as well plots something, although you maybe just want to extract the value and plot something else. Ideally, you could combine extraction and plotting.

  • @Wrzlprmft's solution is using the Linux function tail which is not platform-independent (for Windows you first would have to install such utilities)

Hence, here is a solution:

  • platform-independent and gnuplot-only
  • returns the last x-value and corresponding y-value
  • doesn't create any dummy plot

Script:

### get the last x-value and corresponding y-value
reset session

$Data <<EOD
1     11
2     12
3     13
10    14
5     15
6     16
7     17
8     18
EOD

stats $Data u (lastX=$1,lastY=$2) nooutput
print lastX, lastY
### end of script

Result:

8.0   18.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom Solid
Solution 2
Solution 3 Community
Solution 4