我运行这些代码:
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"))
我可以产生如下结果:
但是我无法得到图例,这意味着最后一行代码不起作用?
答案 0 :(得分:1)
因为vl
具有类xts
,所以当您调用通用函数plot
时,将分派方法plot.xts
。 legend
在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)