有条件地使用日期轴更改ggplot构面背景

Conditionally change ggplot facet background with date axis

facet_gridggplot 结合使用,我试图有条件地更改某些面板的背景,以突出显示我已确定的感兴趣的面板。我正在尝试根据类似问题 here.

的回答来实现这一目标

我理解的想法是首先绘制一个不透明的 geom_rect 图层作为背景,但我认为孤立的问题是在将参数传递给 rect 时,它们与我的实际 x-axis 是日期戳,留下错误

Error: Continuous value supplied to discrete scale

下面是重现问题的最小示例:

dat = read.table(text = "2014-01-25 1  A
2014-02-05 1  A
2014-09-01 1  A
2014-08-26 2  B
2014-12-12 2  C", col.names = c("Date", "Vehicle", "Problem"))

facetcond = data.frame("Vehicle" = 2, "Problem" = "B")

ggplot(dat) +
  theme_bw() + 
  geom_rect(data = facetcond, aes(fill = "red"), 
    xmin = as.Date("2012-01-01"), # I've also tried Inf and 
    xmax = as.Date("2016-01-01"), # -Inf here
    ymin = -Inf, 
    ymax = Inf, alpha = 0.3) +
  geom_bar(aes(x = as.Date(Date), fill = Vehicle), binwidth = 14) +
  facet_grid(Problem~Vehicle, margins = "Problem")

任何帮助将不胜感激,我尝试了多种不同的方法但收效甚微。

错误消息的原因是您试图将美学映射到数据中不存在的列,在这一行中:

geom_rect(data = facetcond, aes(fill = "red"), 

您不是在映射美学,而是告诉 ggplot 用红色填充矩形。该行应该是:

geom_rect(data = facetcond, fill = "red", 

此外,在绘图之前将原始数据框日期转换为 as.Date() 也可以省去一些麻烦。注意我用colClasses直接把数据转换成我想要的class,包括"Date".

这是完整的工作解决方案。

library(ggplot2)

dat = read.table(text = "2014-01-25 1  A
2014-02-05 1  A
                 2014-09-01 1  A
                 2014-08-26 2  B
                 2014-12-12 2  C", 
                 col.names = c("Date", "Vehicle", "Problem"), 
                 colClasses = c("Date", "integer", "factor"))

facetcond = data.frame("Vehicle" = 2, "Problem" = "B")

ggplot(dat) +
  theme_bw() + 
  geom_rect(data = facetcond, fill = "red", 
            xmin = -Inf, # I've also tried Inf and 
            xmax = Inf, # -Inf here
            ymin = -Inf, 
            ymax = Inf, alpha = 0.3) +
  geom_bar(aes(x = Date, fill = Vehicle), binwidth = 14) +
  scale_x_date() +
  facet_grid(Problem~Vehicle, margins = "Problem")