I have a graph with a bar plot and a line chart together. I have no problems to show the labels over the bars but I would like to show them also on top the line chart. The line is showing the sum of the qty service for each date variable. Here is the code:
sample <- data.frame(service_type = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"),
qty = c(38,185,87,29,12,133,2,14,31,2,9,59,60,43,137,135,31,159,15,32,1),
year_week = c("2022 - CW02","2022 - CW02","2022 - CW02","2022 - CW03","2022 - CW03","2022 - CW03","2022 - CW04","2022 - CW04","2022 - CW04","2022 - CW05","2022 - CW05","2022 - CW05","2022 - CW06","2022 - CW06","2022 - CW06","2022 - CW07","2022 - CW07","2022 - CW07","2022 - CW08","2022 - CW08","2022 - CW08"),
xlabel2 = c("Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Jan-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22","Feb-22")
)
sample <- sample %>%
mutate(date = as.Date(paste0(year_week, 1), "%Y - CW%U%u"))
ggplot(sample ) +
aes(x = date, y = qty, fill = service_type) +
geom_col(position = "dodge") +
geom_line(aes(group = 1), stat = "summary", fun = sum, linetype = "dashed", size = 1, color = '#FF507B') +
geom_text(aes(label=qty),
position=position_dodge(7 * 0.9), vjust = 0)+
scale_fill_manual(values = c(A = "#FFC000", B = "#92D050", C = "#AE5AFF"))+
scale_x_date(
date_labels = "%Y - CW%U",
date_breaks = "1 week",
sec.axis = dup_axis(
breaks = as.Date(paste0("15-", unique(sample$xlabel2)), "%d-%b-%y"),
labels = \(x) format(x, "%b-%y")
)
) +
theme_minimal() +
theme(legend.position = "left",
axis.text.x.bottom = element_text(angle=90, hjust=1, vjust = 0.5),
axis.title = element_blank(), legend.title = element_blank(),
panel.grid.minor.x = element_blank())
And the graph is this:
Thanks to everyone sharing some suggestion!
You could add the labels basically the same way as the lines. Use a
geom_text
withstat="summary"
and to add the computed value as label uselabel=after_stat(y)
.