如何使用plot.zoo在每个多图中自定义y轴的颜色和比例?

问题描述

这是我的数据的可复制示例

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),2],df=25)
fit3<-smooth.spline(time(dat),3],df=25)
fit4<-smooth.spline(time(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")

如何修改每个绘图中y轴的颜色和比例以匹配时间序列的相同颜色?

解决方法

创建同时包含序列和平滑样条的dat2,使用window在1965年开始,在screen=中指定各列位于面板1:4中(将循环使用最后4列),并指定最后4列为黑色(即1),或修改颜色以适合。

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))

screenshot

关于评论,对我来说,如果刻度线,标签和轴是黑色的,则似乎更容易阅读,但是如果您想这样做,请使用带有mfrow=循环的for图形参数并指定col.axis通话中的col.labplot.zoo

nc <- ncol(dat)
cols <- 1:nc  # specify desired colors
opar <- par(mfrow = c(nc,1),oma = c(6,5,0),mar = c(0,5.1,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)