如何在R编程中的plot()上添加legend()

问题描述 投票:0回答:1

我运行这些代码:

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")

legend(x = "topleft", 
       cex = 0.4,c("VLIC", "GE", "KO", "AAPL", "MCD"), 
       lty = "l", 
       col = c("black", "green", "red", "violet", "yellow"), 
       text.col = c("black", "green", "red", "violet", "yellow"))

我可以像这样生成结果:

Result Image

但我无法得到传说,这意味着最后一行代码不起作用?

r plot legend
1个回答
1
投票

因为vl有类xts,当你调用泛型函数plot时,调用方法plot.xtslegend与xts情节不是很好,但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)
© www.soinside.com 2019 - 2024. All rights reserved.