0

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)
Ray Tayek
  • 9,841
  • 8
  • 50
  • 90
  • 3
    Please don't post code like `rm(list=ls())` in your questions - no one wants to run that without realizing and lose what they're working on. – Gregor Thomas Jun 27 '23 at 16:03
  • Going to follow this because I cannot get the legend to come up either – stefan_aus_hannover Jun 27 '23 at 16:48
  • i may try ggplot/melt but one would think that is would be easy to plot multiple times series from the same time series object. maybe a using tsibble would be easier. – Ray Tayek Jun 27 '23 at 17:01
  • The problem here is that since you are working with `xts` objects you are not using base R plotting. Instead, the `plot.xts()` function is called which works differently and base `legend()` doesn't appear to be compatible with it. – Robert Hacken Jun 27 '23 at 21:34

0 Answers0