如何用ggplot2绘制加权百分比堆叠条形图及调整数据格式
解决ggplot2绘制加权百分比堆叠条形图的问题
步骤1:将宽格式数据转换为长格式
ggplot2需要长格式数据来实现堆叠条形图的映射,你可以用tidyr::pivot_longer把当前的宽格式数据转换为符合要求的结构:
# 加载所需包(包含ggplot2和tidyr) library(tidyverse) # 转换数据格式 data_long <- data %>% # 将所有Precarious_housing开头的列转为长格式 pivot_longer( cols = starts_with("Precarious_housing"), names_to = "housing_level", values_to = "percentage" ) %>% # 提取等级数字并添加可读标签(可选,但提升图表可读性) mutate( housing_level = str_extract(housing_level, "\\d+") %>% as.integer(), housing_level_label = case_when( housing_level == 0 ~ "无不稳定", housing_level == 1 ~ "轻度不稳定", housing_level == 2 ~ "中度不稳定", housing_level == 3 ~ "重度不稳定" ) )
转换后的data_long会包含以下列:Year、Tenure、housing_level、percentage、housing_level_label,每一行对应一个年份、tenure、住房等级的百分比数据。
步骤2:绘制加权百分比堆叠条形图
因为你的数据已经是加权后的百分比(每行对应等级的占比总和为1),直接用geom_col堆叠即可:
选项1:按Tenure分面展示
如果想把不同Tenure的结果分开展示,用分面功能:
ggplot(data_long, aes(x = factor(Year), y = percentage, fill = housing_level_label)) + geom_col(position = "stack") + # 按Tenure分面 facet_wrap(~Tenure) + # 将Y轴转换为百分比格式 scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + # 设置图表标签 labs( x = "年份", y = "百分比", fill = "住房不稳定等级", title = "不同年份、住房 tenure 下的住房不稳定分布" ) + theme_minimal()
选项2:将Tenure与Year合并为X轴
如果想把Tenure和Year放在同一X轴:
ggplot(data_long, aes(x = interaction(Year, Tenure), y = percentage, fill = housing_level_label)) + geom_col(position = "stack") + scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + labs( x = "年份 & Tenure", y = "百分比", fill = "住房不稳定等级", title = "不同年份、住房 tenure 下的住房不稳定分布" ) + theme_minimal() + # 旋转X轴标签避免重叠 theme(axis.text.x = element_text(angle = 45, hjust = 1))
关键说明
- 你的数据已经是加权计算后的百分比,不需要额外处理权重,直接堆叠即可保证每个条形的高度为100%(对应100%占比)。
position = "stack"是堆叠条形图的核心参数,它会自动将同一X轴分组下的不同fill类别按数值堆叠。
内容的提问来源于stack exchange,提问作者Jules
相关产品推荐
相关产品推荐

