【问题标题】:How to use geom_rect with dates?如何将 geom_rect 与日期一起使用?
【发布时间】:2021-10-01 13:28:21
【问题描述】:

我正在尝试制作带有背景颜色的折线图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。我无法理解这个错误,因为numberdf 数据集和原始p 图表的一部分,工作正常,而不是附加geom_rect 代码的一部分。怎么回事?

【问题讨论】:

    标签: r ggplot2 graph


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-19
      • 2021-02-18
      • 2011-10-22
      • 2021-08-31
      • 1970-01-01
      • 2018-08-09
      • 2017-02-08
      • 2019-12-17
      相关资源
      最近更新 更多