首页 > 解决方案 > 如何使用 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),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")

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

标签: rtime-seriespanelaxiszoo

解决方案


创建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, 1, 1))

截屏

关于评论,对我来说,如果刻度、标签和轴是黑色的,似乎更容易阅读,但如果你想这样做,无论如何都要使用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, 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)

推荐阅读