如何在带有计算参数的循环中使用ggplot?

How to use ggplot in a loop with computed parameters?

我正在尝试在动物园对象的 ggplot 中生成可变数量的矩形(图层)。我想循环执行此操作,因为我事先不知道我需要多少个矩形。这是一个玩具示例。

library("zoo")
library("ggplot2")
set.seed(1)
y <- runif(50, min = 1, max = 2)
start <- as.numeric(as.Date("2018-01-01"))
x <- as.Date(start:(start + 49))
x.zoo <- zoo(y, order.by = x)
## Fill areas
bars <- data.frame(start = c(x[5], x[20], x[35]),
                end = c(x[10], x[25], x[40]))

我可以用这段代码手动绘制这些:

## Plot manually
print(autoplot.zoo(x.zoo, facets = NULL) +
        geom_rect(aes(xmin = bars[1,1],
                  xmax = bars[1,2], ymin = -Inf, ymax = Inf),
                  fill = "pink", alpha = 0.01) +
        geom_rect(aes(xmin = bars[2,1],
                  xmax = bars[2,2], ymin = -Inf, ymax = Inf),
                  fill = "pink", alpha = 0.01) +
        geom_rect(aes(xmin = bars[3,1],
                  xmax = bars[3,2], ymin = -Inf, ymax = Inf),
                  fill = "pink", alpha = 0.01))

这给了我这个想要的图像:

我尝试使用下面的循环,但它只绘制了最后一根柱线。我该怎么做??

## This didn't work but illustrates what I am trying to do
p =  autoplot.zoo(x.zoo, facets = NULL)
for(i in 1:3) {
  p = p + geom_rect(aes(xmin = bars[i,1],
                    xmax = bars[i,2], ymin = -Inf, ymax = Inf),
                    fill = "pink", alpha = 0.01)

}
print(p)

避免 for 循环的一种方法是将 x.zoo 转换为 data.frame 并将数据映射到 geom_line。这样,您就可以将 bars 数据分别映射到 geom_rect

dat <- data.frame(index = index(x.zoo), data.frame(x.zoo))

ggplot() + 
  geom_rect(data = bars, aes(xmin = start, xmax = end, ymin =-Inf, ymax = Inf), fill = 'pink', alpha = .5) +
  geom_line(data=dat, aes(x = index, y = x.zoo))

你不需要循环。 geom_rect 已矢量化

autoplot.zoo(x.zoo, facets = NULL) +
  geom_rect(aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf), data = bars, fill = "pink", alpha = 0.4, inherit.aes = FALSE)