Search code examples
rtime-seriespanelaxiszoo

How to customize color and scale of y axis in each multiple plot using plot.zoo?


This a reproducible example of my data

dat<-data.frame(
prec<-rnorm(650,mean=300),
temp<-rnorm(650,mean = 22),
pet<-rnorm(650,mean = 79),
bal<-rnorm(650,mean = 225))
colnames(dat)<-c("prec","temp","pet","bal")
    
dat<-ts(dat,start = c(1965,1),frequency = 12)
#splines
fit1<-smooth.spline(time(dat),dat[,1],df=25)
fit2<-smooth.spline(time(dat),dat[,2],df=25)
fit3<-smooth.spline(time(dat),dat[,3],df=25)
fit4<-smooth.spline(time(dat),dat[,4],df=25)
    
dat2 <- cbind(dat, fitted(fit1), fitted(fit2), fitted(fit3), fitted(fit4))
plot.zoo(window(dat2, start = 1965), xlab = "", screen = 1:4, 
col = c(1:4, 1, 2, 3, 4),yax.flip = TRUE, bty="n")

How can I modify the color and the scale of the y axes in each plot to match the same color of the time series?


Solution

  • Create dat2 which contains both the series and the smooth splines, use window to start it at 1965, specify in screen= that the the columns be in panels 1:4 (it will recycle for the last 4 columns) and specify that the last 4 columns be black, i.e. 1, or modify colors to suit.

    dat2 <- cbind(dat, fitted(fit1), fitted(fit2), fitted(fit3), fitted(fit4))
    plot.zoo(window(dat2, start = 1965), xlab = "", screen = 1:4, 
      col = c(1:4, 1, 1, 1, 1))
    

    screenshot

    Regarding the comment, to me it seems easier to read if the ticks, labels and axes are black but if you want to do that anyways use the mfrow= graphical parameter with a for loop and specify col.axis and col.lab in the plot.zoo call:

    nc <- ncol(dat)
    cols <- 1:nc  # specify desired colors
    opar <- par(mfrow = c(nc, 1), oma = c(6, 0, 5, 0), mar = c(0, 5.1, 0, 2.1))
    for(i in 1:nc) {
      dat1965 <- window(dat[, i], start = 1965)
      plot(as.zoo(dat1965), col = cols[i], ylab = colnames(dat)[i], col.axis = cols[i],
        col.lab = cols[i])
      fit <- smooth.spline(time(dat1965), dat1965, df = 25)
      lines(cbind(dat1965, fitted(fit))[, 2])  # coerce fitted() to ts
    }
    par(opar)
    mtext("4 plots", line = -2, font = 2, outer = TRUE)