【问题标题】:How to use ggplot in a loop with computed parameters?如何在具有计算参数的循环中使用 ggplot?
【发布时间】:2018-03-20 13:22:37
【问题描述】:

我正在尝试在动物园对象的 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)

【问题讨论】:

  • 错误是什么?
  • 抱歉 - 我说错了。这个循环的化身只绘制最后一个柱,而不是前两个。它不会抛出错误
  • 这与您的问题无关,但as.Date() 会给我一个错误,除非我提供origin = 参数指定从多少天开始计数。
  • @divibisan,OP 使用了zoo 包。 @Ernie,请包括重要的包。

标签: r plot ggplot2 zoo


【解决方案1】:

您不需要循环。 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) 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 2023-01-07
      • 2021-09-09
      • 2021-05-20
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多