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

Gnuplot折线图按Y值设置颜色问题求助(附多图代码)

解决Gnuplot按Y值为折线分段上色的问题

核心思路

Gnuplot默认折线为单一颜色,要实现Y>0红、Y<0蓝的效果,有两种可靠方案:拆分数据分别绘图(适配smooth场景)或用动态颜色变量结合离散调色板。


方案1:拆分数据+分别平滑绘图(推荐适配smooth csplines)

此方法避免插值点颜色混乱,适合需要平滑曲线的场景:

  1. 基础设置(适配multiplot)
# 定义红蓝线条样式
set style line 1 lc "red" lw 2
set style line 2 lc "blue" lw 2

# 自动提取X轴标签(基于数据第一列)
stats 'your_data.txt' nooutput
set xtics (for [i=0:int(STATS_records-1)] word(stringcolumn(1,i+1),1) i)
  1. 在multiplot子图中绘图
# 进入multiplot环境(假设你已设置布局)
set multiplot layout 2,1

# 第一个子图:按Y值拆分后分别平滑绘图
plot \
    '< awk ''$2>0'' your_data.txt' using 0:2 smooth csplines ls 1 notitle, \
    '< awk ''$2<0'' your_data.txt' using 0:2 smooth csplines ls 2 notitle

# 第二个子图(根据你的需求调整)
# ... 其他绘图代码

unset multiplot

方案2:动态颜色变量+离散调色板

若不需要拆分数据,可通过给每个点分配颜色索引实现:

# 定义离散调色板(0=红,1=蓝)
set palette defined (0 "red", 1 "blue")
set cbrange [0:1]
unset colorbox # 隐藏颜色条(可选)

# 自动设置X轴标签
stats 'your_data.txt' nooutput
set xtics (for [i=0:int(STATS_records-1)] word(stringcolumn(1,i+1),1) i)

# 绘图:第三列为颜色索引(Y>0则0,否则1)
plot 'your_data.txt' using 0:2:(($2>0)?0:1) smooth csplines with lines linecolor palette notitle

你之前的问题原因解析

  1. using 2:xtic(1):2导致偏移:第一个2被当作X坐标,而非行号,X轴用Y值替代自然会偏移。正确X坐标应使用行号(0)或索引列。
  2. linecolor palette报错:该选项必须在using中提供第三列作为Z值(颜色依据),你未指定第三列所以触发"not enough columns"错误。
  3. smooth与调色板兼容问题:smooth会生成插值点,若直接用原始点的颜色索引,插值点可能出现跨正负的颜色过渡,拆分数据绘图可彻底避免此问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:02:40