如何在R中基于含非数值数据的CSV创建百分比堆叠面积图
实现百分比堆叠面积图的R方案
问题分析
你需要的是按age3(年龄组)分组,展示racethn4(种族类别)占比的百分比堆叠面积图。原始数据是单条应答记录,无法直接绘图,必须先做分组统计计算占比。
完整实现代码
1. 准备工作
# 安装依赖包(首次运行) install.packages("tidyverse") # 加载工具包 library(tidyverse) # 读取数据 df <- read_csv("https://raw.githubusercontent.com/fivethirtyeight/data/master/masculinity-survey/raw-responses.csv")
2. 数据汇总与占比计算
# 统计每个年龄组内各种族的人数,再计算百分比 summary_data <- df %>% group_by(age3, racethn4) %>% summarise(total = n(), .groups = "drop") %>% group_by(age3) %>% mutate(percent = (total / sum(total)) * 100) %>% filter(!is.na(age3), !is.na(racethn4)) # 过滤缺失值
3. 绘制堆叠面积图
ggplot(summary_data, aes(x = age3, y = percent, fill = racethn4, group = racethn4)) + geom_area(position = "stack", alpha = 0.7) + labs( x = "年龄组", y = "占比(%)", fill = "种族类别", title = "各年龄组种族占比分布" ) + ylim(0, 100) + # 固定Y轴范围为0-100 theme_bw() # 使用简洁主题
关键细节
- 原始数据是单条应答,必须先通过
group_by+summarise统计分组人数,再计算每组内的百分比,这就是你需要的Y轴数值(percent列)。 group = racethn4参数是必要的,确保ggplot正确识别每个种族的分组轨迹,避免绘图异常。- 如果想要更平滑的曲线效果,可以将
geom_area替换为geom_smooth(method = "loess", se = FALSE, position = "stack"),但静态堆叠面积图更适合展示占比分布。
内容的提问来源于stack exchange,提问作者user19692638
相关产品推荐
相关产品推荐

