如何在R的ggplot年龄标准化死亡率图中叠加死亡数柱状图
解决方案
要在现有图表中添加年度死亡数的第二轴柱状图,需分两步调整:先扩展数据处理流程计算年度总死亡数,再通过ggplot的双轴功能实现可视化。
步骤1:扩展数据处理,同时计算死亡率和总死亡数
原代码仅计算了年龄标准化死亡率,我们需要在分组汇总时额外计算每年的总死亡数:
library(tidyverse) library(scales) processed_data <- dummmortalitydata %>% pivot_longer(-(1:4)) %>% separate(name, into = c('measure', 'year'), sep = "(?=\\d{4})") %>% rename(ReferencePopulation = ReferecePopulation) %>% pivot_wider(names_from = measure, values_from = value) %>% mutate(NoOfDeaths = ifelse(NoOfDeaths > LocalPopulation, LocalPopulation, NoOfDeaths)) %>% rowwise() %>% mutate(mortality = NoOfDeaths / LocalPopulation, lower = prop.test(NoOfDeaths, LocalPopulation)$conf[1], upper = prop.test(NoOfDeaths, LocalPopulation)$conf[2]) %>% group_by(year) %>% summarize( mortality = sum(mortality * ReferencePopulation/sum(ReferencePopulation)), lower = sum(lower * ReferencePopulation/sum(ReferencePopulation)), upper = sum(upper * ReferencePopulation/sum(ReferencePopulation)), total_deaths = sum(NoOfDeaths) # 新增:计算年度总死亡数 ) %>% ungroup()
步骤2:绘制双轴图表
使用ggplot的sec_axis功能添加第二Y轴,需对死亡数进行缩放以匹配左轴的数值范围,避免图表失衡:
# 计算缩放比例:用死亡率最大值除以死亡数最大值 scale_factor <- max(processed_data$mortality) / max(processed_data$total_deaths) ggplot(processed_data, aes(x = year)) + # 绘制死亡数柱状图(缩放后适配左轴) geom_col(aes(y = total_deaths * scale_factor), fill = "lightblue", alpha = 0.7, width = 0.4) + # 绘制死亡率的误差棒和点(偏移位置避免重叠) geom_errorbar(aes(y = mortality, ymin = lower, ymax = upper), width = 0.2, position = position_nudge(x = 0.2)) + geom_point(aes(y = mortality), color = "darkred", size = 3, position = position_nudge(x = 0.2)) + # 配置双Y轴 scale_y_continuous( name = "年龄标准化死亡率(95%CI)", labels = percent, sec.axis = sec_axis(~./scale_factor, name = "年度总死亡数") ) + labs(x = "年份") + theme_classic(base_size = 16) + # 为两个轴标题设置不同颜色,提升可读性 theme( axis.title.y = element_text(color = "darkred"), axis.title.y.right = element_text(color = "steelblue") )
关键说明
- 缩放比例:双轴的核心是将死亡数按比例缩放,使其数值范围与死亡率匹配,避免其中一个系列被压缩到不可见。
- 位置偏移:使用
position_nudge让死亡率的点和误差棒稍微偏移,避免与柱状图重叠。 - 颜色区分:为两个系列和轴标题设置不同颜色,帮助读者快速区分不同数据。
内容的提问来源于stack exchange,提问作者skpak
相关产品推荐
相关产品推荐

