如何在Gnuplot单图中设置柱状图为固定小间距紧密排列?
在Gnuplot中调整柱状图间距,实现紧密排列并保留小间隔
数据文件(data.txt)
amount cost profit 64 22.915949 48.15697753 128 15.424979 56.41929322 256 9.473054 49.80545598 512 6.685107 96.8453052 1024 4.897494 56.82355225
现有代码
set boxwidth 40.0 abs set style fill solid set y2tics set ytics nomirror set grid y set bmargin at screen 0.2 set tmargin at screen 0.9 # Set the graph title and axis labels set title "Title" set xlabel "Amount" set ylabel "Cost" set y2label "Profit" plot 'data.txt' using 1:2:xtic(1) with boxes axes x1y1, \ 'data.txt' using 1:3 w lp pt 7 lw 2 ps 1 axes x1y2 pause -1
问题原因
你的x轴是数值型轴,数据点的x值(64、128、256等)本身间隔呈指数增长,直接用using 1绘制会让柱状图的间距跟着x轴数值走,导致后面的柱子间距越来越大。
解决方法
将x轴转为类别型轴,用数据的行号作为x坐标,让每个柱子均匀分布,再通过boxwidth控制宽度来保留小间隔:
- 把柱状图的
using 1:2:xtic(1)改成using 0:2:xtic(1),0代表数据的行号(从1开始),这样每个柱子的x位置是1、2、3、4、5,均匀排列 - 将
set boxwidth从绝对数值(40.0 abs)改成相对值(比如0.8),相对值是相对于柱子的默认间距(默认1个单位),0.8的宽度会让柱子之间保留0.2的固定小间隔 - 折线图的x坐标也要对应改成行号,即
using 0:3,保证折线和柱子对齐
修改后的完整代码
set boxwidth 0.8 # 相对宽度,控制柱子间距 set style fill solid set y2tics set ytics nomirror set grid y set bmargin at screen 0.2 set tmargin at screen 0.9 set title "Title" set xlabel "Amount" set ylabel "Cost" set y2label "Profit" # 用行号(0)作为x坐标,实现均匀排列 plot 'data.txt' using 0:2:xtic(1) with boxes axes x1y1, \ 'data.txt' using 0:3 w lp pt 7 lw 2 ps 1 axes x1y2 pause -1
额外调整选项
- 如果需要更窄的间隔,可增大
boxwidth(比如0.9),间隔会更小;反之减小boxwidth(比如0.7),间隔会变大 - 若坚持用绝对宽度,可写成
set boxwidth 0.8 abs,但相对值更适配类别轴的均匀分布
内容的提问来源于stack exchange,提问作者Bibrak
相关产品推荐
相关产品推荐

