如何在ggplot中用两个数据集将折线图叠加到分组条形图上?
问题解决:ggplot叠加折线时出现
object 'ReportAge' not found错误 错误原因
你在全局图层的aes()中定义了fill = ReportAge,添加geom_line()时,它会默认继承这个全局美学映射,但你的dt2数据框中不存在ReportAge列,因此触发报错。
解决方法
有两种可行方案:
- 给
geom_line()设置inherit.aes = FALSE,完全不继承全局美学映射 - 在
geom_line()的aes()中显式覆盖fill映射(如fill = NULL)
同时注意:原代码中mutate(as.factor(ReportAge))未将转换结果赋值给列,会导致ReportAge仍为数值型,需修正为ReportAge = as.factor(ReportAge)。
修正后的完整代码
library(tidyverse) library(lubridate) 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(ReportAge = 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() # 方案1:禁用全局美学继承 graph2 <- graph + geom_line(data = dt2, mapping = aes(x = ReportDate, y = OldReports), color = "red", inherit.aes = FALSE) # 方案2:显式覆盖fill映射 # graph2 <- graph + # geom_line(data = dt2, mapping = aes(x = ReportDate, y = OldReports, fill = NULL), # color = "red") print(graph2)
内容的提问来源于stack exchange,提问作者Andrew Chastain
相关产品推荐
相关产品推荐

