You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gnuplot 6.0多列数据直方图循环着色问题求助

解决Gnuplot循环绘制直方图的叠绘与着色问题

问题背景

在Gnuplot 6.0环境下,数据文件采用3×3数组格式(每行包含3个数值):

1 0.12 172.7
2 0.11 183.8
3 0.75 55.4

尝试用循环脚本绘制直方图时遇到两个核心问题:

  • 使用boxes lc i循环着色时出现叠绘,最终仅显示同一数值
  • 改用u (column(3)):xtic(3)无法区分不同数据的颜色

原使用的循环脚本如下:

gnuplot -p << EOF
set terminal png
set term pngcairo dashed
set title  "Title" font ",15"
set ylabel "y" font ",15"
set xlabel "x" font ",15"
set style fill solid 1.0
 
filename2(n) = sprintf("data%03.0f.dat", n)
outfile  (n) = sprintf("data%03.0f.png", n)

set boxwidth 1.0 
set style fill solid 1.0
set tics font ", 16"

do for [N=15:15] {
    set output outfile(N)
    infile = filename2(N)

    array scale[4]
    scale[1] = 'r/r_0:  80 - 100%' 
    scale[2] = '    50 - 80%'
    scale[3] = '    30 - 50%'
    scale[4] = '    10 - 30%'

plot for [i=1:3] filename2  (N) u(i): (column(3)):xtic(3) w boxes lc i  notitle,\
        for [i=1:3] keyentry w boxes lc i title scale[i]  at graph 0.22, graph (0.99-0.045*i)                
       }
EOF 

问题分析

  1. 叠绘原因:原脚本循环时,每次读取整个数据文件,且x轴统一使用column(3)作为位置,导致三个直方图完全重叠在同一x坐标上,最终仅显示最后绘制的柱子。
  2. 着色失效原因:若直接用u (column(3)):xtic(3),所有柱子的x位置相同,且没有区分不同列的逻辑,循环着色无法生效。

解决方法

核心思路是为每一列数据分配独立的x轴位置,避免重叠,同时保留循环着色逻辑:

修改后的脚本

gnuplot -p << EOF
set terminal pngcairo dashed
set title  "Title" font ",15"
set ylabel "y" font ",15"
set xlabel "x" font ",15"
set style fill solid 1.0
 
filename2(n) = sprintf("data%03.0f.dat", n)
outfile(n) = sprintf("data%03.0f.png", n)

set boxwidth 0.25  # 缩小柱子宽度,适配并排显示的间距
set tics font ", 16"
set xtics nomirror  # 优化x轴刻度显示

do for [N=15:15] {
    set output outfile(N)
    infile = filename2(N)

    array scale[4]
    scale[1] = 'r/r_0:  80 - 100%' 
    scale[2] = '    50 - 80%'
    scale[3] = '    30 - 50%'
    scale[4] = '    10 - 30%'

    # 为每列数据生成偏移后的x坐标:行号作为基础,i控制左右偏移
    plot for [i=1:3] infile u (row_number() + (i-2)*0.3):i w boxes lc i notitle, \
         for [i=1:3] keyentry w boxes lc i title scale[i] at graph 0.22, graph (0.99-0.045*i)
    
    # 手动设置x轴刻度,对应每行的第三列数值
    set xtics ('172.7' 1, '183.8' 2, '55.4' 3)
    replot
}
EOF

关键修改点

  • x轴位置偏移:使用row_number() + (i-2)*0.3为同一行的三个柱子分配不同的x坐标,实现并排显示,避免重叠
  • 柱子宽度调整:将boxwidth设为0.25,适配偏移后的柱子间距,防止相邻行的柱子互相干扰
  • 手动设置刻度:通过set xtics将x轴刻度对应到每行的第三列数值,保证刻度显示与原数据一致

效果说明

修改后,每行的三个数据会以不同颜色的柱子并排显示在对应x刻度位置,既解决了叠绘问题,又实现了循环着色,同时保留了原数据的x轴标签信息。

内容的提问来源于stack exchange,提问作者SofaScientist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:33:12