gnuplot

Find local maximum of data files in gnuplot


I have a list of data (two columns) and I want to plot in gnuplot only the value for which my second column has a local maximum.

To do so I would like to see if the second column of the ith row is bigger than the (i-1) and (i+1)th rows.


Solution

  • It can be done and I was bored enough to do it. I generated the following set of random data:

    5191
    29375
    23222
    32118
    3185
    32355
    17173
    8734
    28850
    20811
    5956
    6950
    28560
    25770
    4630
    28272
    10035
    7209
    19428
    26187
    30784
    20326
    12865
    23288
    20924
    

    Plotting the values against their position in the list looks like this:

    enter image description here

    You can spot the local maxima right away from the graph above. Now I can process the data points storing the two previous values (both x and y coordinates) in temporary variables, when I identify a maximum, I plot the data point:

    # Select the columns of your data file that contain x and y data
    # (usually 1 and 2 respectively)
    xcolumn=0
    ycolumn=1
    
    plot "data" u (column(xcolumn)):(column(ycolumn)) w l, \
    "data" u (column(0)==0 ? (last2y=column(ycolumn), \
    last2x=column(xcolumn), 1/0) : column(0)==1 ? (lasty=column(ycolumn), \
    lastx=column(xcolumn), 1/0) : lastx) \
    : \
    ( column(0) < 2 ? 1/0 : (last2y < lasty && \
    column(ycolumn) < lasty) ? (value=lasty, last2y=lasty, last2x=lastx, \
    lasty=column(ycolumn), lastx=column(xcolumn), value) : (last2y=lasty, \
    last2x=lastx, lasty=column(ycolumn), lastx=column(xcolumn), 1/0)) pt 7
    

    enter image description here