r - 如何使用 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 轴的颜色和比例以匹配时间序列的相同颜色?
解决方案
创建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.lab
plot.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)
推荐阅读
- c# - 反射 - 如何设置值
- d3.js - 如何按值而不是键对 dc.js 饼图进行排序
- python - 如何使用正则表达式从此列表中制作字典?
- c++ - 评估多项式时跳过 0 系数的有效方法是什么?
- php - Laravel - 跨数据库关系
- c# - FluentAssertions ShouldBeEquivalent 可以与 c#9 记录类型一起使用吗?
- r - 谁能告诉我为什么我一直收到错误“mtcars$am 中的错误:$ 运算符对原子向量无效”?
- python - 如何通过使用单个赋值屏蔽另一个 numpy 数组来创建新的 numpy 数组
- r - ggplot颜色条标签日期格式
- swift - macOS Swift 应用程序:imkxpc_getApplicationProperty:reply:使用不正确的属性值 4 调用,保释