如何用ggplot2绘制仅展示单模态的分组百分比条形图(R语言)
绘制单一模态的分组百分比条形图解决方案
核心思路
要只展示某一关系状态(如"non stable")在各年龄组的百分比,需先筛选出目标类别,再计算该类别在对应年龄组中的占比,最后绘制单一条形图而非堆叠图。
方法一:直接筛选目标类别后计算占比
library(tidyverse) library(scales) # 原始数据 age10 <- c("18-34","35-54", "55+", "55+","35-54","18-34","18-34","35-54","35-54","35-54") relation <- c("stable","non stable", "non stable", "stable", "stable", "stable", "non stable", "non stable", "stable", "stable") df <- data.frame(age10,relation) # 数据处理:计算各年龄组中非稳定关系的百分比 df_single <- df %>% group_by(age10) %>% mutate(group_total = n()) %>% # 统计每个年龄组的总人数 filter(relation == "non stable") %>% # 只保留非稳定关系的数据 summarise(non_stable_percent = n()/group_total) # 计算占比 # 绘图 ggplot(df_single) + aes(x = age10, y = non_stable_percent) + geom_bar(stat = "identity", fill = "#2ca02c") + # 单一颜色填充条形 scale_y_continuous(labels = percent) + # 将数值转为百分比格式 labs(x = "年龄组", y = "百分比", title = "各年龄组非稳定关系占比")
方法二:基于原汇总数据调整
如果想保留原汇总逻辑,也可以在已分组统计的基础上筛选目标类别并计算占比:
# 基于原代码的汇总数据调整 df1 <- df %>% group_by(age10, relation) %>% summarise(n = n(), .groups = "drop") %>% group_by(age10) %>% mutate(total = sum(n), percent = n/total) %>% # 计算每组总数及目标类别占比 filter(relation == "non stable") # 筛选目标类别 ggplot(df1) + aes(x = age10, y = percent) + geom_bar(stat = "identity", fill = "#d62728") + scale_y_continuous(labels = percent) + labs(x = "年龄组", y = "百分比", title = "各年龄组非稳定关系占比")
关键修改点
- 筛选目标类别:通过
filter(relation == "non stable")剔除不需要的关系状态数据 - 计算组内占比:按年龄组分组后统计总人数,再计算目标类别的占比,而非用
position = "fill"生成堆叠图 - 简化绘图映射:移除
fill = relation映射(仅展示单一类别),直接用固定颜色填充条形
内容的提问来源于stack exchange,提问作者lpambout
相关产品推荐
相关产品推荐

