在比例直方图上叠加计数折线与活跃位置数量文本
解决方案:叠加计数折线与比例直方图并添加位置计数文本
没问题,我帮你梳理一下实现思路和代码,完全符合你的需求:
首先,我们需要先预处理数据,计算出每个时间点的活跃位置总数、各护理人员类型的计数和比例。另外,为了让计数折线能和比例直方图共用同一坐标轴(避免双轴的歧义),我们可以把活跃位置数归一化到0-1的范围(除以最大的活跃位置数,也就是你的数据里的4),这样就能直接叠加在比例图上,还不用额外显示计数的坐标轴。
第一步:数据预处理
用dplyr来统计所需的指标:
library(tidyverse) # 你的原始数据 dt <- tibble( "location" = c("A", "B", "C", "D", "A", "B", "C", "A", "B", "C", "A", "B", "A", "A", "A"), "months.since.start" = c(0,0,0,0,1,1,1,2,2,2,3,3,4,5,6), "carer" = c("HCA", "nurse", "nurse", "dr", "HCA", "dr", "nurse", "HCA", "dr", "nurse", "dr", "HCA", "dr", "nurse", "HCA") ) # 计算各时间点的活跃位置数、护理人员计数和比例 plot_data <- dt %>% group_by(months.since.start) %>% mutate(total_locations = n()) %>% # 每个时间点的活跃位置总数 ungroup() %>% count(months.since.start, carer, total_locations, name = "carer_count") %>% group_by(months.since.start) %>% mutate(carer_prop = carer_count / total_locations) %>% # 护理人员比例 ungroup() # 提取活跃位置数的文本数据,并归一化到0-1范围 location_stats <- plot_data %>% distinct(months.since.start, total_locations) %>% mutate(norm_locations = total_locations / max(total_locations)) # 归一化适配比例坐标轴
第二步:分层绘制图形
先画堆叠的比例直方图,再叠加归一化后的活跃位置折线,最后添加位置计数文本:
ggplot() + # 绘制比例直方图(对应你说的图B) geom_col(data = plot_data, aes(x = months.since.start, y = carer_prop, fill = carer), position = "stack", alpha = 0.8) + # 叠加活跃位置数折线(原计数直方图转成的折线,对应图A) geom_line(data = location_stats, aes(x = months.since.start, y = norm_locations), color = "darkred", size = 1.2, group = 1, linetype = "solid") + # 添加活跃位置数量文本(原图A的geom_text内容) geom_text(data = location_stats, aes(x = months.since.start, y = norm_locations + 0.03, # 稍微上移避免和折线重叠 label = paste("Active Locations:", total_locations)), color = "darkred", fontface = "bold", size = 3.5) + # 调整图表标签和样式 labs(x = "Months Since Start", y = "Proportion of Carer Roles", fill = "Carer Type") + scale_fill_brewer(palette = "Set2") + theme_minimal() + theme(panel.grid.minor = element_blank())
关键说明:
- 归一化的原因:把活跃位置数除以最大值4,将数值压缩到0-1区间,完美适配比例直方图的y轴范围,不需要额外显示计数的坐标轴,完全符合你的需求。
- 分层顺序:先画柱状图,再画折线和文本,确保折线和文本在最上层,不会被柱状图遮挡。
- 可选双轴版本(不推荐):如果你坚持不想归一化,可以用双轴实现,但双轴容易造成读者误解刻度对应关系。如果需要的话,我可以再提供双轴的代码,但更推荐上面的归一化方案。
内容的提问来源于stack exchange,提问作者SorenK
相关产品推荐
相关产品推荐

