Search code examples
gnuplot

How to get a y value for a x coordinate


In gnuplot, if I have a line curve using some data points and I want to know what value of x(in a line) correspond what value of y(apart from the data file I have). How can I do it in gnuplot?


Solution

  • You can do linear interpolation with gnuplot. While plotting the data you assign in a "serial evaluation" (check help operators binary, serial evaluation) the previous coordinate to x0,y0 and the current coordinate to x1,y1. Between those you are doing linear interpolation and writing the interpolated value to yi. In a second plot command you can plot this value as single value via '+' u (myX):(yi) every ::0::0 w labels. Check help special-filenames, help every, help labels.

    edit: change script to work also for decreasing x-values.

    Script:

    ### interpolate a value
    reset session
    
    $Data <<EOD
     1   1
     3   9
     5  25
     7  49
    EOD
    
    xi = 2
    Interpolate(xi) = x0==x1 ? (y0+y1)/2. : (y1-y0)/(x1-x0)*(xi-x0) + y0
    set key top left noautotitle
    
    plot x1=y1=NaN $Data u (x0=x1,x1=$1):(y0=y1,y1=$2, (x0-xi)*(x1-xi)<=0 ? \
            yi=Interpolate(xi):0, y1) w lp pt 7 lc "red" ti "data", \
         '+' u (xi):(yi):(sprintf("(%g|%g)",xi,yi)) every ::0::0 \
            w labels point pt 7 lc "blue" offset 0,1 ti "interpolated"
    ### end of script
    

    Result:

    enter image description here