Trying to add a legend to my plot (please see below). The sample code I used works fine (using "center"). My code below does not get a legend (at least not one that I can see as I have poor vision).
Edit 1: I was able to get a legend by using this question.
addLegend("center", on=1,
legend.names = c("SPY", "IWM"),
lty=c(1, 1), lwd=c(2, 1),
col=c("black", "blue"))
Original code:
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)