plotgnuplotskip

gnuplot: how to skip rows with 0 in a column?


I need to extract the row of data where the absolute difference of y(block_1)-pt is less than a certain limit. If more than one row satisfies this condition, I need to retrieve the row with the smallest difference.

$Data <<EOD
# block_1   # block_2
x y         x y
1 1979.2    2 2027
1 1598.6    2 1591.4
1 1430.8    2 1401.6
1 1544.7    2 1923.7
1 1953.3    2 1677
1 1288.8    2 1311.1
1 1741.3    2 1689.3
1 1791.1    2 2015.8
EOD

set key autotitle columnhead

pt = 1953.1
limit = 0.5

absDiff(col,x) = abs( column(col) - x ) < limit

set table $Temp
    plot $Data u ( absDiff( 2, pt ) ):( $4 ) w table
unset table

print $Temp

The result is:

 0       2027
 0       1591.4
 0       1401.6
 0       1923.7
 1       1677
 0       1311.1
 0       1689.3
 0       2015.8

How can I skip all rows that contain a 0 in the first column?


Solution

  • If you are using gnuplot>5.4.0 you can use the experimental feature "conditional writing to a table" (check help with table). If you are bound to versions <5.4.0, there are other solutions.

    If you change your plot with table command to

    plot $Data u ( absDiff( 2, pt ) ):4 w table if absDiff( 2, pt )
    

    the result will be:

     1       1677
    

    Addition: finding the minimum difference without giving a limit and using stats.

    You better skip the line x y x y because it is no valid data line and it will shift the row index by one. Row indices are zero-based.

    Script: (requires gnuplot>=5.0, because of use of datablocks, stats works also with earlier 4.x versions)

    ### find minimum difference and corresponding row
    reset session
    
    $Data <<EOD
    # block_1   # block_2
    x y         x y
    1 1979.2    2 2027
    1 1598.6    2 1591.4
    1 1430.8    2 1401.6
    1 1544.7    2 1923.7
    1 1953.3    2 1677
    1 1288.8    2 1311.1
    1 1741.3    2 1689.3
    1 1791.1    2 2015.8
    EOD
    
    pt = 1953.1
    
    stats $Data u 4:(abs($2-pt)) skip 1 nooutput
    
    print sprintf("Minimum difference is: %g",STATS_min_y)
    print sprintf("Located in row:        %g",STATS_index_min_y)
    print sprintf("Value in column 4 is:  %g",STATS_pos_min_y)
    ### end of script
    

    Result:

    Minimum difference is: 0.2
    Located in row:        4
    Value in column 4 is:  1677