在Plot() 函数中,无法添加 legend() 的解决办法
2018-09-06 本文已影响29人
2010jing
最近新手接触 R 语言,在做一道练习的时候,利用plot()进行画折线图,在最后一步调用legend() 添加图例的时候,死活都没有产生出来。
直接贴出 脚本
library("quantmod")
symbols=c('^VLIC','GE','KO','AAPL','MCD')
getSymbols(symbols,src='yahoo',from="2012-02-01",to="2013-02-01")
#obtain adjusted closed
VLICad = VLIC$VLIC.Adjusted
GEad= GE$GE.Adjusted
KOad=KO$KO.Adjusted
AAPLad=AAPL$AAPL.Adjusted
MCDad = MCD$MCD.Adjusted
#compute cumulative sum (cumsum) of daily returns (Delt)
#Remove first term of the series, with [-1,], since cumsum is not defined for it.
vl = cumsum((Delt(VLICad)*100)[-1,])
ge = cumsum((Delt(GEad)*100)[-1,])
ko = cumsum((Delt(KOad)*100)[-1,])
ap = cumsum((Delt(AAPLad)*100)[-1,])
md = cumsum((Delt(MCDad)*100)[-1,])
###range of values for the plot
lim = c(min(vl,ge,ko,ap,md),max(vl,ge,ko,ap,md))
plot(vl,main="",ylim=lim,xlab="dates",ylab="% benefits")
lines(ge,col="green")
lines(ko,col="red")
lines(ap,col="violet")
lines(md,col="yellow")
## THE FOLLOWING SCRIPT DOES NOT WORK!!!
legend("topright",c("VLIC","GE","KO","AAPL","MCD"),col=c("black","green","red","violet","yellow"),text.col=c("black","green","red","violet","yellow"))
最后生成出来的是
result.png
于是乎,R 可以查看帮助, 输入这个脚本执行,会弹出页面帮助
?legend
弹出的页面
?legend
页面介绍了这个方法,具体参数说明,以及使用实例。
开始一看,十多个参数。。。有点慌,还好不是每个都要用。
前后对比,没有毛病啊!!! 就是不出来图例...
网上搜。。。没有找到解决办法~
查看别人家的demo,可是很顺利出来。
别人家的demo
模仿别人的来写,还是不行,简直要崩溃...
最后在网上发帖子求教,最后有@Dan Y 大牛给出了答案:
Because vl has class xts, when you call the generic function plot, the method plot.xts is dispatched. legend doesn't play very nicely with xts plots, but xts::addLegend does.
言下之意,就是legend() 支持不是那么好,可以使用xts的addLegend()方法替换。在他的提示下执行如下脚本:
colvec <- c("black","green","red","violet","yellow")
xts::addLegend(legend.loc="topleft", legend.names=c("VLIC","GE","KO","AAPL","MCD"),lty = 1, col=colvec, text.col=colvec, bg="white", bty=1)
# 直接如下代码也行
# addLegend(legend.loc="topright", legend.names=c("VLIC","GE","KO","AAPL","MCD"),lty = 1, col=colvec, text.col=colvec, bg="white", bty=1)
最后结果
终于成功参考资料