如何将 geom_rect 与日期一起使用?

时间:2021-07-25 05:33:10

标签: r ggplot2 graph

我正在尝试使用背景颜色 like the accepted answer here 制作折线图。我可以制作一个简单的折线图,但是当我添加矩形几何图形时,它会引发错误。

为线条和矩形设置数据:

library(ggplot2)
  
df <- data.frame(
  date = c('1980-09-01', '1981-12-01', '1982-03-01', '1983-06-01', '1984-08-01'),
  number = c(4,8,7,9,2)
)
df$date <- as.Date(df$date)

rects <- data.frame(
  name = c('A', 'B', 'C'),
  start = c('1980-09-01', '1981-05-15', '1983-02-22'),
  end = c('1981-05-15', '1983-02-22', '1984-05-23')
)
rects$start <- as.Date(rects$start)
rects$end <- as.Date(rects$end)

制作并显示一个简单的折线图:

p <- ggplot(data=df, aes(x=date, y=number)) +
  geom_line() +
  geom_point() +
  scale_x_date(date_breaks = "1 year", date_labels = "%Y")
p

到目前为止它工作正常。但是,尝试在背景中添加矩形:

p + geom_rect(data = rects, mapping=aes(xmin = start, xmax = end,
                                        ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)

这会引发错误 Error in FUN(X[[i]], ...) : object 'number' not found。我无法理解此错误,因为 number 是运行良好的 df 数据集和原始 p 图的一部分,而不是附加 geom_rect 代码的一部分。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

由于您已将 aes(x=date, y=number) 置于全局 ggplot 对象中,因此所有层都将继承这些映射。由于这些值不适用于 geom_rect 层中的数据,因此您需要显式关闭继承。

  geom_rect(data = rects, inherit.aes=FALSE, mapping=aes(xmin = start, xmax = end,
                                    ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)

或将这些值重新映射为 NULL

  geom_rect(data = rects, mapping=aes(xmin = start, xmax = end, x=NULL, y=NULL,
                                    ymin = -Inf, ymax = Inf, fill = name), alpha = 0.4)
相关问题