R ggplot:在柱状图上添加周服务总量趋势线报错求助
问题原因与解决方法
报错原因
你设置的geom_line(aes(y= qty, group = interaction(service_type,date)))把数据拆成了每个服务类型+每个日期的独立分组,每组只有1个观测值。折线图需要同一组内至少有2个连续的点才能连线,所以ggplot抛出这个提示。
更关键的是,你的需求是展示每周服务总数量的趋势线,但原代码里用的qty是单个服务类型的数量,逻辑上根本不符合需求。
修正步骤与代码
1. 先计算每周的服务总数量
先对原数据按周分组,算出每周所有服务类型的总qty:
library(dplyr) library(ggplot2) # 原数据 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")) # 计算每周总服务量 weekly_total <- sample %>% group_by(year_week, date) %>% summarise(total_qty = sum(qty), .groups = "drop")
2. 绘制带总趋势线的柱状图
用原数据画分类型柱状图,用汇总后的weekly_total画趋势线,同时调整折线位置避免被遮挡:
sample %>% ggplot() + # 绘制分服务类型的柱状图 aes(x = date, fill = service_type, weight = qty) + geom_bar(position = "dodge") + # 添加每周总数量的趋势线(用汇总数据) geom_line(data = weekly_total, aes(x = date, y = total_qty, group = 1), color = "black", size = 1, linetype = "solid") + # 可选:添加总数量的标签,偏移10避免遮挡 geom_text(data = weekly_total, aes(x = date, y = total_qty + 10, label = total_qty), size = 3, color = "black") + 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), axis.title = element_blank(), legend.title = element_blank())
关键改动说明
- 新增
weekly_total数据框,专门存储每周的总服务量,解决了趋势线的数据来源问题 geom_line使用汇总数据,设置group = 1确保所有点属于同一组,能正常连线- 给折线添加了偏移的标签,方便查看每周总数量,可根据需求调整偏移量
内容的提问来源于stack exchange,提问作者romina
相关产品推荐
相关产品推荐

