I’m trying to generate a dodged bar graph that shows the distribution of report ages per report day and overlay the total reports over a critical report age for each day.
When I add the line to the bar graph I get an error:
Error in `geom_line()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error:
! object 'ReportAge' not found
Here is my reproducible example:
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")
In this graph looks fine, but graph2 throws the above error.