如何在gnuplot中创建行堆叠且分组的柱状图?
实现gnuplot归一化行堆叠且分组交错的柱状图
核心思路
gnuplot原生不支持同时启用rowstacked和clustered的直方图样式(后指定的参数会覆盖前者),但可以通过手动X轴偏移结合rowstacked样式,配合数据归一化处理,实现需求效果,无需用boxxyerror从零构建。
步骤1:数据归一化
先对每组数据做归一化处理,确保每个分组内的堆叠柱体总和为1:
# 定义两组原始测试数据 $Set1 <<EOD Group1 0.2 0.3 0.5 Group2 0.1 0.4 0.5 Group3 0.3 0.2 0.5 EOD $Set2 <<EOD Group1 0.4 0.3 0.3 Group2 0.2 0.5 0.3 Group3 0.1 0.6 0.3 EOD # 归一化第一组数据 stats $Set1 using (sum=$2+$3+$4) nooutput set table $NormSet1 plot $Set1 using 1:($2/sum):($3/sum):($4/sum) with table unset table # 归一化第二组数据 stats $Set2 using (sum=$2+$3+$4) nooutput set table $NormSet2 plot $Set2 using 1:($2/sum):($3/sum):($4/sum) with table unset table
步骤2:配置绘图样式
设置行堆叠直方图样式,调整柱宽以适配分组偏移:
set style data histogram set style histogram rowstacked set style fill solid border -1 # 填充样式 set boxwidth 0.35 # 单组柱宽,预留偏移空间 set xtics nomirror # 仅底部显示X轴刻度 set ylabel "归一化占比" set title "行堆叠+分组交错柱状图"
步骤3:绘制偏移后的分组堆叠柱体
通过$0 ± 偏移量手动调整两组柱体的X轴位置,实现交错排列:
# 绘制第一组(左偏移) plot for [col=2:4] $NormSet1 using ($0 - 0.35):col:xtic(1) \ title "类别".strcol(col-1), \ # 绘制第二组(右偏移) for [col=2:4] $NormSet2 using ($0 + 0.35):col \ title "类别".strcol(col-1)."(第二组)"
关键问题解决
你之前遇到的Too many columns in using specification报错,是因为使用histogram样式时,using语法不能直接混合X轴偏移和数据列的错误写法。正确的写法是在using中先指定偏移后的X坐标,再指定数据列,让histogram样式正确解析每个堆叠层的数值。
替代方案(并排分组)
如果接受分组并排而非交错,也可以用newhistogram实现,但这种方式两组会完全分开,而非交错:
set style histogram clustered gap 1 set style histogram rowstacked set boxwidth 0.8 plot $NormSet1 using 2:xtic(1) title "类别1", \ '' using 3 title "类别2", \ '' using 4 title "类别3", \ newhistogram offset 1, \ $NormSet2 using 2 title "类别1(第二组)", \ '' using 3 title "类别2(第二组)", \ '' using 4 title "类别3(第二组)"
内容的提问来源于stack exchange,提问作者theozh
相关产品推荐
相关产品推荐

