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

R语言绘制高斯密度图时如何在右上角生成(media,sigma)配对值图例

问题原因

你目前代码不符合预期的核心原因是连续两次调用legend函数且都指定放在右上角,两个图例直接重叠覆盖,同时也没有将media和sigma的取值配对成你需要的格式。

解决方法

只需要调用一次legend函数,提前将对应位置的MEDIA和SIGMA取值拼接为要求的配对格式即可,修改后的完整代码如下:

passo = 0.01
MEDIA = c(1/4, 1/2, 1, 2, 4)
SIGMA = c(5, 4 ,3, 2, 1)
len = length(MEDIA)
x = seq(0, 10, passo)

plot(x=NULL, y=NULL, xlim=c(0, 10), ylim=c(0, 0.6), xlab='x', ylab='densità' )
title("densità gaussiana")

for (i in 1:len){
    media = MEDIA[i]
    sigma = SIGMA[i]
    lines(x, dnorm(x, media, sigma), type='l', col=i)
}

# 构造配对的图例标签
legend_labels <- paste0(MEDIA, ", ", SIGMA)
# 仅调用一次legend,设置title为要求的首行内容
legend('topright', 
       title = "(media, sigma)",
       legend = legend_labels, 
       col = 1:len,  
       lty = 1, 
       cex = 0.4)

效果说明

运行修改后的代码,右上角的图例就会完全符合你要求的格式:

(media, sigma)
0.25, 5
0.5, 4
1, 3
2, 2
4, 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:06:03