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

Gnuplot技术问题:如何为堆叠柱状图的平均值条形设置不同颜色

解决Gnuplot堆叠柱状图中最后一个条形的颜色自定义问题

问题原因

你遇到的错误是因为Gnuplot不允许在linecolor rgb参数中直接使用字符串条件表达式(比如strcol(1) eq "Average")。linecolor rgb仅接受固定的颜色字符串,无法动态计算颜色值。

解决方案

我们可以通过数值索引映射颜色的方式实现需求:

  1. 预先定义不同的线型(linetype)并绑定对应颜色
  2. 在plot命令的using子句中,根据行是否为"Average"计算对应的线型索引
  3. 使用linecolor variable让Gnuplot根据索引选择颜色

修改后的完整脚本

set terminal png size 1000, 500
set output "bars.png"
set title "Trends"
set style data histograms
set style histogram rowstacked
set yrange [0:*]
set style fill solid
set boxwidth 0.9
set xlabel "Dates"  # 修正原脚本中轴标签颠倒的问题
set ylabel "Clicks"
set xtics right rotate by 45
set datafile separator ","

# 定义颜色映射:普通行和Average行分别使用不同线型
set linetype 1 lc rgb "#0000ff"  # 普通行的Direct颜色
set linetype 2 lc rgb "#ff0000"  # Average行的Direct颜色
set linetype 3 lc rgb "#00ff00"  # 普通行的Indirect颜色
set linetype 4 lc rgb "#ff50ff"  # Average行的Indirect颜色

plot newhistogram, \
     "data.csv" using 2:(strcol(1) eq "Average" ? 2 : 1):xtic(1) title "Direct" linecolor variable, \
     "" using 3:(strcol(1) eq "Average" ? 4 : 3) title "Indirect" linecolor variable

关键说明

  • (strcol(1) eq "Average" ? 2 : 1):判断当前行第一列是否为"Average",是则返回2(对应Average的Direct颜色),否则返回1(对应普通Direct颜色)
  • linecolor variable:告诉Gnuplot使用using子句中最后一个数值作为线型索引,从而匹配预先定义的颜色
  • 修正了原脚本中x轴和y轴标签颠倒的问题(原脚本xlabel为"Clicks"但实际显示日期,ylabel为"Dates"但显示点击数)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:01:05