0

The following creates a two column XTS object to serve as example data.

quantmod::getSymbols(c('SPY','IWM'),
                     src  = 'yahoo', 
                     from = '2010-01-01', 
                     to   = '2021-02-01',
                     auto.assign = TRUE, 
                     warnings = FALSE)
close <- cbind(SPY$SPY.Close, IWM$IWM.Close)

The following makes a nice plot of both columns as a function of time, but the legend does not appear. The legend command looks like it executes in that it does not return an error, but no legend is made on the plot.

qualityTools::plot(close, col=1:ncol(close))
legend('topleft', legend=colnames(close), 
       col=1:ncol(close), lty=1, cex=0.5)

Plot of XTS object without legend

I also tried the following. It makes a plot of both columns and I get a legend. However, the as.ts() function turns the time index from the XTS object into an incremental counter from 1 to ncol(close) rather than real dates. As a result, the time axis in the plot is also a simple, incremental counter rather than real dates.

closets <- stats::as.ts(close)
qualityTools::plot(closets, plot.type='single', col = 1:ncol(closets))
legend('topleft', legend=colnames(closets), 
       col=1:ncol(closets), lty=1, cex=0.5)

Plot of TS object with legend but a period counter rather than real time axis

Any thoughts on how to get a legend on the first plot attempt of the XTS object? If not, I'd settle for a better time axis on the 2nd plot attempt of the TS object.

raml5
  • 3
  • 2

1 Answers1

2

When you are using quantmod, you can either use chartSeries or just plot (which is a call to plot.xts) to plot the timeseries.

At the moment of writing the package qualityTools is no longer on cran, but is archived due to some errors that have not been fixed by the package maintainer.

An example using plot:

plot.xts(SPY$SPY.Close, ylim = c(0,500), main = "")
lines(IWM$IWM.Close)
addLegend("topleft", on=1, 
          legend.names = c("SPY", "IWM"), 
          lty=c(1, 1), lwd=c(2, 1),
          col=c("black", "blue"))

enter image description here

phiver
  • 23,048
  • 14
  • 44
  • 56
  • Thanks, that was very helpful. It looks like I really only need two lines to handle any number of columns in the XTS object: xts::plot.xts(close); xts::addLegend("topleft", legend.names = names(close), lty=1, col=1:ncol(close)) – raml5 Oct 08 '21 at 20:15