如何在gnuplot中实现统计柱(bin)宽度均匀一致?
解决gnuplot直方图空区间柱形宽度异常的问题
问题描述
当前生成的直方图存在空区间(如10-15)时,对应柱形会被自动加宽填充空间,期望所有统计柱(bin)宽度保持一致。
当前使用的gnuplot代码:
binwidth=5 bin(x,width)=width*floor(x/width) plot 'Module 2 Mod*100.txt' using (bin($1,binwidth)):(1.0) \ smooth freq with boxes linecolor rgb "#FFCCE5" title ''

解决方法
核心是强制指定柱形宽度,同时确保空区间也能生成宽度一致的柱形,以下是三种实用方案:
方案1:手动指定柱宽+补全空区间数据
- 在绘图命令中添加
boxwidth binwidth,强制每个柱子宽度等于设定的区间宽度:
binwidth=5 bin(x,width)=width*floor(x/width) plot 'Module 2 Mod*100.txt' using (bin($1,binwidth)):(1.0) \ smooth freq with boxes linecolor rgb "#FFCCE5" boxwidth binwidth title ''
- 针对空区间,在数据文件中补充对应区间中点的行(如12.5对应10-15区间),y值设为0,确保空区间也会显示宽度一致的空柱子。
方案2:改用直方图样式固定柱宽
如果数据已按区间统计完成,可切换到直方图样式强制统一宽度:
binwidth=5 set style histogram clustered gap 1 # gap参数控制柱子间的间距 set style fill solid linecolor rgb "#FFCCE5" plot 'Module 2 Mod*100.txt' using 2:xtic(1) with histogram title ''
注:此方式要求数据文件整理为两列,第一列是区间标签(如"0-5"),第二列是对应计数。
方案3:自动补全空区间(无需修改原始数据)
利用gnuplot的stats命令获取数据范围,自动生成所有区间的空数据,再合并统计:
binwidth=5 # 获取数据的x轴范围 stats 'Module 2 Mod*100.txt' using 1 min_x = binwidth*floor(STATS_min/binwidth) max_x = binwidth*ceil(STATS_max/binwidth) # 生成所有区间的中点临时文件 set table 'temp_bins.txt' plot [min_x:max_x] '-' using (x):(0) with points min_x max_x+binwidth end unset table # 合并临时空区间数据与原始数据,再统计频率绘图 plot '<cat temp_bins.txt "Module 2 Mod*100.txt"' using (bin($1,binwidth)):(1.0) \ smooth freq with boxes linecolor rgb "#FFCCE5" boxwidth binwidth title ''
内容的提问来源于stack exchange,提问作者schrodingers_cat
相关产品推荐
相关产品推荐

