Search code examples
gnuplotnumerical-methods

How can I plot the derivative of a graph in gnuplot?


I have a set of measurements of a variable over time. I have these measurements in a file called "results" with this format:

# time sample
0      5
12     43
234    342

etc...

I can easily plot this in gnuplot with:

plot "results"

Is there any way to plot the derivative of these measurements with regard to time (i.e. dsample/dt) directly from gnuplot, or do I have to calculate the derivative separately and plot that directly in gnuplot?


Solution

  • You can do it by defining a function to take the derivative:

    #!/usr/bin/env gnuplot
    
    set term pngcairo
    set output 'test.png'
    
    # derivative functions.  Return 1/0 for first point, otherwise delta y or (delta y)/(delta x)
    d(y) = ($0 == 0) ? (y1 = y, 1/0) : (y2 = y1, y1 = y, y1-y2)
    d2(x,y) = ($0 == 0) ? (x1 = x, y1 = y, 1/0) : (x2 = x1, x1 = x, y2 = y1, y1 = y, (y1-y2)/(x1-x2))
    
    set key bottom left Left reverse
    
    # offset for derivatives (half the x spacing)
    dx = 0.25
    
    plot 'data.dat' title 'data', \
         '' u ($1-dx):(d($2)) title '1-variable derivative', \
         '' u ($1-dx):(d2($1,$2)) title '2-variable derivative', \
         '' u ($1-dx):(d2($1,$2)) smooth csplines title '2-variable derivative (smoothed)'
    

    d2(x,y) (which is probably what you are looking for) just computes rise over run (delta y over delta x) at all but the first data point, and d(y) computes delta y in the same way. Given this data file

    0.0 1
    0.5 2
    1.0 3
    1.5 4
    2.0 5
    2.5 3
    3.0 1
    

    The result is

    enter image description here