【发布时间】: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,请包括重要的包。