Search code examples
rloopsplotxts

Change name in xts loop plots


I have a loop on four xts plots:

basket <- cbind(AAPLG, GEG, SPYG, WMTG)
tickers <- c("AAPL", "GE", "SPY", "WMT")
par(mar = c(3, 3, 3, 3))
par(mfrow=c(2,2))
for (i in 1:4){
print(plot.xts(x = basket[, i], xlab = "Time", ylab = "Cumulative Return",
     , major.ticks= "years",
     minor.ticks = FALSE, col = "black"))
}

I have come as far as removing the sample space at the top of each plot, from the SO post: Changes in plotting an XTS object However, is there a way to change the headings for each figure to the ticker symbols above?So when running the loop basket[, i] will be replaced by tickers <- c("AAPL", "GE", "SPY", "WMT")

Data sample:

structure(c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073, 
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889, 
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567, 
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013, 
1.04571606282071), class = c("xts", "zoo"), index = structure(c(946944000, 
947030400, 947116800, 947203200, 947462400), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
    NULL, c("new.close", "new.close.1", "new.close.2", "new.close.3"
    )))

PLot of four cumulative returns

This is the plot I have so far. All called basket [ ,i] which isn't very informative.

Also: The ylab and xlab isn't shown in the plots even though a set high margins. Does anyone know a solution for that?


Solution

  • Call ticker object function for main in the plot

    for (i in 1:4){
      print(plot.xts(x = basket[, i], xlab = "Time", ylab = "Cumulative Return",
                     major.ticks= "years", minor.ticks = FALSE, 
                     col = "black", main = tickers[i]))
    }