基于R ggplot绘制多人口统计组的Likert量表堆叠条形图
用ggplot绘制多人口分组的Likert量表堆叠条形图
问题说明
需要为Likert量表调查绘制堆叠条形图,对比单问题(Q2)在多个人口统计分组中的回答分布,包括整体受访者、不同性别、不同宗教重要性群体等。现有代码仅能生成单条整体堆叠条形,需整合多分组数据实现多条形对比。
解决方案步骤
核心思路是将不同分组的数据整理为统一的长格式,让ggplot可以一次性渲染所有分组的条形。
1. 加载依赖包
library(tidyverse)
2. 导入示例数据
survey <- structure(list(Gender = c("Man", "Woman", "Woman", "Decline to answer", "Man", "Man", "Woman", "Man", "Woman", "Man"), Religion_Importance = c("Very important", "Not too important", "Not too important", "Not important at all", "Somewhat important", "Very important", "Not too important", "Not important at all", "Somewhat important", "Very important" ), Q2 = structure(c(1L, 2L, 2L, 3L, 1L, 3L, 1L, 2L, 4L, 1L), levels = c("Always or almost always", "Generally", "Not generally", "Never or almost never", "NA"), class = "factor")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
3. 整理多分组数据
将整体、性别、宗教重要性三个维度的分组数据合并为统一结构:
# 1. 整体受访者数据 overall_data <- survey %>% filter(!is.na(Q2)) %>% mutate(group_type = "整体受访者", group = "整体") %>% select(group_type, group, Q2) # 2. 性别分组数据 gender_data <- survey %>% filter(!is.na(Q2)) %>% mutate(group_type = "性别", group = Gender) %>% select(group_type, group, Q2) # 3. 宗教重要性分组数据 religion_data <- survey %>% filter(!is.na(Q2)) %>% mutate(group_type = "宗教重要性", group = Religion_Importance) %>% select(group_type, group, Q2) # 合并所有数据 combined_data <- bind_rows(overall_data, gender_data, religion_data) # 统一Q2的因子顺序(修正原代码中的Q20笔误) combined_data <- combined_data %>% mutate(Q2 = factor(Q2, levels = c("Always or almost always", "Generally", "Not generally", "Never or almost never")))
4. 绘制堆叠条形图
ggplot(combined_data, aes(x = group, fill = Q2)) + geom_bar(position = "fill", width = 0.7) + # position="fill"实现百分比堆叠 coord_flip() + # 翻转坐标轴,方便阅读长标签 facet_wrap(~group_type, scales = "free_y", ncol = 1) + # 按分组类型分面,自由调整y轴 labs(y = "占比(%)", x = "", fill = "Q2回答") + scale_y_continuous(labels = scales::percent) + # 将y轴转为百分比显示 theme_bw() + theme( strip.background = element_rect(fill = "#f0f0f0"), strip.text = element_text(face = "bold") )
关键调整说明
- 如果不需要展示某类分组(如
Decline to answer),可在对应数据块添加filter(Gender != "Decline to answer") - 可通过
scale_fill_brewer()或scale_fill_manual()自定义填充颜色 - 调整
facet_wrap的ncol参数可以改变分面的列数,比如ncol=2会分成两列显示
内容的提问来源于stack exchange,提问作者haley
相关产品推荐
相关产品推荐

