我正在尝试生成一个闪避条形图,显示每个报告日的报告年龄分布,并将每天的总报告覆盖在关键报告年龄上。
当我将线条添加到条形图时,出现错误:
Error in `geom_line()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error:
! object 'ReportAge' not found
这是我的可重现示例:
dt1 <- expand.grid("ReportDate" = seq(ymd("2024-04-25"),
ymd("2024-05-01"),
by = "day"),
"ReportAge" = seq(1,7,1)) %>%
mutate(n = sample(0:10, n(), replace = TRUE)) %>%
arrange(ReportDate) %>%
mutate(as.factor(ReportAge))
dt2 <- dt1 %>%
filter(as.numeric(ReportAge) > 5) %>%
group_by(ReportDate) %>%
summarize(OldReports = sum(n))
graph <- dt1 %>%
ggplot(aes(x = ReportDate, y = n, fill = ReportAge)) +
geom_bar(stat = "identity",
color = "black",
position = position_dodge2(width = 0.9,
preserve = "single")) +
geom_text(aes(y= -1, label = ReportAge),
color = "black",
position = position_dodge2(width = 0.9, preserve = "single"),
size = 3.5) +
geom_text(aes(label = n),
color = "red",
vjust = -0.3,
position = position_dodge2(width = 0.9, preserve = "single")) +
guides(fill = guide_legend(override.aes = list(size = 0.5))) +
scale_x_date(date_breaks = "day", date_labels = "%b %d") +
theme_minimal()
graph2 <- graph +
geom_line(data = dt2, mapping = aes(x = ReportDate, y = OldReports), color = "red")
在此图中看起来不错,但 graph2 抛出了上述错误。
改变它
graph2 <- graph +
geom_line(data = dt2, mapping = aes(x = ReportDate, y = OldReports, fill=NULL), color = "red")
geom_line
正在继承您对 aes()
的调用中的 ggplot()
。基本上,您为每个图层设置 fill = ReportAge
,当您添加额外的 geom_line
时,dt2
数据源没有名为 ReportAge
的列,因此您会收到错误。您可以通过设置为 NULL 来“取消映射”值