使用ggplot2绘制按Group分组、Year分面的Type百分比堆叠条形图
绘制按Group分组、Year分面的Type百分比堆叠条形图
要实现需求,我们可以先对原始数据做占比统计,再用ggplot2完成可视化,具体步骤如下:
步骤1:加载工具包并处理数据
用dplyr做数据汇总,ggplot2负责绘图:
# 加载所需包 library(dplyr) library(ggplot2) # 原始数据 Year <- c(2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021) Group <- c(1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2) Type <- c(1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0) df <- data.frame(Year, Group, Type) # 计算每个Year+Group组合下,不同Type的占比 df_summary <- df %>% group_by(Year, Group, Type) %>% tally() %>% # 统计各组合的样本数 mutate(percent = n / sum(n) * 100) # 转换为百分比
步骤2:绘制百分比堆叠条形图
这里提供两种实现方式,效果一致:
方式1:基于预处理的百分比数据绘图
ggplot(df_summary, aes(x = factor(Group), y = percent, fill = factor(Type))) + geom_bar(stat = "identity") + facet_wrap(~Year) + # 按年份分面展示 labs( x = "分组(Group)", y = "百分比(%)", fill = "类型(Type)", title = "按Group分组、Year分面的Type百分比堆叠条形图" ) + theme_minimal() + scale_y_continuous(labels = scales::percent_format(scale = 1)) # 将数值转为百分比格式显示
方式2:直接用position = "fill"生成百分比堆叠
无需提前计算占比,更简洁:
ggplot(df, aes(x = factor(Group), fill = factor(Type))) + geom_bar(position = "fill") + facet_wrap(~Year) + labs( x = "分组(Group)", y = "百分比(%)", fill = "类型(Type)", title = "按Group分组、Year分面的Type百分比堆叠条形图" ) + theme_minimal() + scale_y_continuous(labels = scales::percent_format())
最终生成的图会以年份为分面,每个分面内按Group分组,堆叠条形展示不同Type的占比情况。
内容的提问来源于stack exchange,提问作者Jenn0804
相关产品推荐
相关产品推荐

