我有一个包含条形图和折线图的图表。 我可以毫无问题地在条形图上显示标签,但我想也将它们显示在折线图的顶部。该行显示每个日期变量的服务数量总和。 这是代码:
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())
图表是这样的:
感谢大家分享一些建议!
您可以按照与线条基本相同的方式添加标签。将
geom_text
与 stat="summary"
结合使用,并将计算值添加为标签,使用 label=after_stat(y)
。
library(ggplot2)
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
) +
geom_text(
aes(label = after_stat(y), group = 1),
stat = "summary", fun = sum, 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()
)