0

In some cases you might need to resample your data. How can this be done platform-independently with gnuplot? Below is one attempt.

The dataset $Dummy contains the interpolated values, however, with a lot of unnecessary lines containing NaN. The dataset $DataResampled finally contains the desired data.

My question is: can this be done simpler?

The code:

### resampling data with linear interpolation
reset session

$Data <<EOD
0   1
1   4
2   10
5   15
10  5
20  11
EOD

# get the x-range
stats $Data u 1 nooutput
MinX = STATS_min
MaxX = STATS_max
Resamples=20
# or alternatively fix the step size 
# StepSize=1
# Resamples = int(MaxX-MinX)/StepSize+1

Interpolate(xi) = y0 + (y1-y0)/(x1-x0)*(xi-x0) 
x1=y1=NaN

# resample the data
set print $DataResampled
set table $Dummy
do for [i=1:Resamples] {
    xi = MinX + (i-1)*(MaxX-MinX)/(Resamples-1)
    Flag=0
    plot $Data u (x0=x1, x1=$1, y0=y1, y1=$2,\
        (xi>=x0 && xi<=x1 && Flag==0 ? (Flag=1, yi=Interpolate(xi), xi) : NaN)): \
        (Flag==1 ? yi : NaN) with table
    print sprintf("%g\t%g",xi,yi)
}
unset table
set print

set xrange[-1:21]
plot $Data u 1:2 w lp pt 6 ps 2 lc rgb "black" t "original data",\
     $DataResampled u 1:2 w lp pt 7 lc rgb "web-green" t "resampled with linear interpolation",\
     $Dummy u 1:2 w impulses lc rgb "red" not
### end of code

The result: enter image description here

theozh
  • 22,244
  • 5
  • 28
  • 72
  • Generally speaking, that is a bit away from gnuplot's typical usage. Arrays and such widen the programming-like capabilities, but gnuplot sticks more to the philosophy of Unix tools: do one thing, and do it properly. Usually one would use an external tool or script for resampling, like `plot '< resample.py'`, which is also platform independant. For your special case an implementation of `smooth linear` could be worth a feature request, but gnuplot will remain a plotting tool, and not a data processor. – Christoph Jan 25 '19 at 17:19
  • ok, I partly agree. If I have to use external tools for very basic tasks of data preparation, e.g. like transposing, sorting, resampling, merging, appending or special file listings and additionally want to ensure platform independence by using Python, what would be the reasons **not** to switch to Matplotlib? Don't get me wrong, I like gnuplot very much. – theozh Jan 26 '19 at 08:13
  • @Christoph, some time go, I placed a feature request for linear interpolation, i.e. `smooth linear` (https://sourceforge.net/p/gnuplot/feature-requests/518/), however, no response so far... – theozh Apr 15 '21 at 06:10

0 Answers0