将facet_grid
与ggplot
一起使用,我试图有条件地更改某些面板的背景,以突出显示我感兴趣的内容。我试图按照类似问题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")
我们将非常感谢任何帮助,我尝试了许多不同的方法但收效甚微。
答案 0 :(得分:1)
您的错误消息的原因是您尝试将美学映射到数据中不存在的列,在此行中:
geom_rect(data = facetcond, aes(fill = "red"),
您没有映射美学,而是告诉ggplot
用红色填充矩形。该行应该是:
geom_rect(data = facetcond, fill = "red",
此外,通过在绘图之前将原始数据框日期转换为as.Date()
,您还可以省去一些麻烦。请注意,我使用colClasses
将数据直接转换为我想要的类,包括“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")