I would like to automatically find the nearest value to zero with gnuplot of a column. I tried this but it doesn't work :
stats 'file.dat' u abs($1)
and then I should have the nearest value to zero by taking STATS_min
-0.018492 -0.00369832
-0.0106795 -0.00352183
-0.00612481 -0.0016998
-0.00221856 -0.00160066
0.00168769 -0.00148317
0.00559394 -0.00135358
0.00950019 -0.00119879
0.0134064 -0.00102774
Do you have any ideas ? Thanks
If you did the following and mind the ()
around abs($1)
:
stats $Data u (abs($1)) nooutput
print STATS_min
you would get: 0.00168769
, which would be correct for your current data.
However, be careful, if there was a value e.g. -0.0001
, this would return +0.0001
.
Hence you have to use "two" columns for stats
, one for finding the minimal distance to zero and the other one for returning the value with the original sign.
So, on purpose, below I inserted a line -0.0001 -0.99999
Script:
### get nearest value to zero
reset session
$Data <<EOD
-0.018492 -0.00369832
-0.0106795 -0.00352183
-0.00612481 -0.0016998
-0.00221856 -0.00160066
-0.0001 -0.99999
0.00168769 -0.00148317
0.00559394 -0.00135358
0.00950019 -0.00119879
0.0134064 -0.00102774
EOD
stats $Data u 1:(abs($1)) nooutput
print STATS_pos_min_y
### end of script
Result:
-0.0001
Addition:
Here is an alternative suggestion without stats
. In case you want to label the extracted point, you can extract the coordinates during the plot command, i.e. you go through the data only once.
Script:
### get nearest value to zero
reset session
$Data <<EOD
-0.018492 -0.00369832
-0.0106795 -0.00352183
-0.00612481 -0.0016998
-0.00221856 -0.00160066
-0.0001 -0.0015
0.00168769 -0.00148317
0.00559394 -0.00135358
0.00950019 -0.00119879
0.0134064 -0.00102774
EOD
set key noautotitle
set yzeroaxis
plot x0=y0=NaN $Data u (x0!=x0?x0=$1:abs($1)<abs(x0)?(y0=$2,x0=$1):$1):2 w p pt 7 lc "red", \
'+' u (x0):(y0):(sprintf("(%g,%g)",x0,y0)) every ::::0 w labels offset 0,-1 left
### end of script
Result: