不使用histogram样式,用boxes绘制gnuplot聚类柱状图问题
解决gnuplot手动用boxes绘制聚类柱状图的位置排列问题
要实现同组多柱状图并列的效果且不依赖set style data histogram,核心是手动计算每个系列的x轴偏移量,让同组内的boxes错开排列,同时保持每组整体与x轴刻度对齐。
示例数据(data.txt)
假设我们有3个类别组,每组包含3个数据系列:
# Category Series1 Series2 Series3 1 5 7 6 2 3 4 5 3 8 6 7
手动偏移的基础实现代码
# 全局样式设置 set style fill solid 0.7 # 设置填充透明度 set boxwidth 0.25 # 单个柱状图宽度 set xtics 1,1,3 # x轴刻度对应3个类别组 set yrange [0:10] # y轴范围适配数据 # 计算组内偏移基准:让同组柱状图整体居中于刻度 num_series = 3 # 每组的系列数量 base_offset = -(num_series - 1)*0.25/2 # 起始偏移量 # 绘制每个系列,手动添加偏移量 plot 'data.txt' using ($1 + base_offset):2 with boxes title 'Series1', \ '' using ($1 + base_offset + 0.25):3 with boxes title 'Series2', \ '' using ($1 + base_offset + 0.5):4 with boxes title 'Series3'
更灵活的循环版本(适合多系列场景)
如果系列数量较多,用do for循环自动生成绘制命令,避免重复代码:
num_series = 3 box_width = 0.25 base_offset = -(num_series - 1)*box_width/2 set style fill solid 0.7 set boxwidth box_width set xtics 1,1,3 set yrange [0:10] # 循环绘制每个系列,自动计算偏移 plot for [i=2:num_series+1] 'data.txt' \ using ($1 + base_offset + (i-2)*box_width):i \ with boxes title sprintf('Series%d', i-1)
关键细节说明
- 偏移量计算:
base_offset的作用是让同组的第一个柱状图向左偏移,确保整个组的boxes在x轴刻度上方居中,避免偏左或偏右。 - box宽度控制:
boxwidth需设置为小于或等于系列间的偏移步长(示例中为0.25),防止同组内的柱状图重叠。 - 刻度对齐:
xtics设置为类别组的索引,保证每组柱状图与对应刻度对齐。
内容的提问来源于stack exchange,提问作者flav
相关产品推荐
相关产品推荐

