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

如何解决R语言基础绘图中图例缺失的问题?

绘图图例显示问题及解决

我尝试给绘图添加图例,用带center参数的示例代码能正常显示,但自己写的代码里图例要么不显示,要么因视力问题无法看清。

编辑1:已解决
参考相关问题后,使用addLegend函数成功显示图例,代码如下:

addLegend("center", on=1, 
          legend.names = c("SPY", "IWM"), 
          lty=c(1, 1), lwd=c(2, 1),
          col=c("black", "blue"))

原始代码

library(roll) # do not use library(RcppRoll)!
getSymbols("^GSPC",src="yahoo",from="2015-01-01",to = "2020-06-04")
y<-GSPC$GSPC.Close
plot(y)
standardize<-function(ts) { as.xts(apply(ts, 2, function(x) x / x[1])) }
y<-standardize(GSPC$GSPC.Close)
plot(y)
y$m<-rollmean(y$GSPC.Close,k=100)
plot(y$m)
y$rolling<-roll_sd(y$GSPC.Close,100)
plot(y$rolling)

par(mfrow=c(1,1))
plot(y$GSPC.Close,                          
     y$Index,
     type = "l",
     col = 2,
     xlab = "Date",
     ylab = "$")
# Add line graphs of other two dataset
lines(y$m,                            
      y$Index,
      type = "l",
      col = 3)

lines(y$rolling,                            
      y$Index,
      type = "l",
      col = 4)

# Add legend in the center
legend("center",                          
       c("$","ma", "sd"),
       lty = 1,
       col = 2:4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:22:37