在Gnuplot中设置xrange后,如何通过stats获取y最大值对应的x?
Gnuplot中获取指定x范围内y最大值对应x值的解决方法
当设置xrange后,stats命令返回的STATS_index_max_y是过滤后数据的相对索引,直接用这个索引读取原数据会得到错误结果,以下是两种纯Gnuplot的解决思路:
方法一:自定义变量跟踪最大值(推荐)
不用依赖xrange过滤,而是在stats遍历数据时,通过条件判断筛选x范围,同时实时更新最大值对应的x值,完全避开索引偏移问题:
# 初始化变量,存储最大值及对应x max_y = -infinity max_x = NaN # 遍历数据,仅处理x在200-1000区间的点 stats 'your_data_file.txt' using 1:3 nooutput \ if ($1 >= 200 && $1 <= 1000) \ do for [i=0:*] { if ($3 > max_y) { max_y = $3 max_x = $1 } } # 输出结果 print "y最大值对应的x: ", max_x print "y最大值: ", max_y
方法二:先过滤数据到临时文件
如果必须使用xrange,可以先将指定范围内的数据导出到临时文件,再对临时文件执行stats,此时的索引就是临时文件的绝对索引,可直接对应正确的x值:
# 将x在200-1000的数据导出到临时表 set table 'filtered_temp.txt' plot 'your_data_file.txt' using 1:3 with table unset table # 对过滤后的数据统计最大值索引 stats 'filtered_temp.txt' using 1:3 nooutput # 根据索引提取对应x值 target_x = NaN stats 'filtered_temp.txt' using (target_x = ($0 == STATS_index_max_y) ? $1 : target_x) nooutput # 输出结果 print "y最大值对应的x: ", target_x
内容的提问来源于stack exchange,提问作者atapaka
相关产品推荐
相关产品推荐

