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

如何为Gnuplot中用arrow绘制的竖线添加图例?

Gnuplot竖线添加图例的解决方法

针对你用set arrow绘制竖线无法添加图例的问题,这里提供两种直接可行的方案:

方案1:改用plot命令直接绘制竖线(推荐)

Gnuplot 5.0及以上版本支持直接用x=常数的语法绘制竖线,这样竖线会作为plot的一个系列自动加入图例。修改后的完整代码如下:

reset
set encoding utf8
set terminal pdfcairo size 20cm,20cm font "STIX Two Math, 22" enhanced
set output "straight-lines.pdf"
#
set grid linetype 0 linewidth 1 dashtype 3 linecolor "grey50" # dotted
set border linewidth 0.5
set samples 1000
set xrange [-10:10]
set yrange [-10:10]

array M[5] = [0, -2, 3, 0.5, -0.8]
array C[5] = [2, 0, 3.5, -4, -0.2]
array NC[5] = ["dark-green", "orange-red", "steelblue", "dark-yellow", "brown"]

set title "Straight Lines: 𝑦 = 𝑚𝑥 + 𝑐"
# 将竖线作为plot的一个系列,自动生成图例
plot for [i = 1:5:1] M[i]*x + C[i] linecolor rgbcolor(NC[i]) linewidth 3 title sprintf("%1.1f %s %1.1f", M[i], "𝑥 + ", C[i]), \
     x=4 linewidth 3 linecolor "gray50" title "𝑥 = 4"

如果你的Gnuplot版本低于5.0,可以用参数方程实现:

# 替换上述plot行中的x=4部分
set parametric
plot for [i = 1:5:1] M[i]*x + C[i] linecolor rgbcolor(NC[i]) linewidth 3 title sprintf("%1.1f %s %1.1f", M[i], "𝑥 + ", C[i]), \
     4, t linewidth 3 linecolor "gray50" title "𝑥 = 4"
set noparametric

方案2:保留set arrow,手动添加图例条目

如果坚持用箭头绘制竖线,可以通过set key add命令手动向图例中添加匹配样式的条目:

reset
set encoding utf8
set terminal pdfcairo size 20cm,20cm font "STIX Two Math, 22" enhanced
set output "straight-lines.pdf"
#
set grid linetype 0 linewidth 1 dashtype 3 linecolor "grey50" # dotted
set border linewidth 0.5
set samples 1000
set xrange [-10:10]
set yrange [-10:10]

array M[5] = [0, -2, 3, 0.5, -0.8]
array C[5] = [2, 0, 3.5, -4, -0.2]
array NC[5] = ["dark-green", "orange-red", "steelblue", "dark-yellow", "brown"]

set arrow from 4, -10 to 4, 10 nohead linewidth 3 linecolor "gray50"
# 手动添加匹配箭头样式的图例条目
set key add "𝑥 = 4" linewidth 3 linecolor "gray50"

set title "Straight Lines: 𝑦 = 𝑚𝑥 + 𝑐"
plot for [i = 1:5:1] M[i]*x + C[i] linecolor rgbcolor(NC[i]) linewidth 3 title sprintf("%1.1f %s %1.1f", M[i], "𝑥 + ", C[i])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:57:32