You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R新手如何基于Likert量表数据绘制指定样式100%堆叠条形图

实现方案

你可以使用ggplot2快速完成符合要求的100%堆叠条形图,具体调整步骤和代码如下:

1. 加载依赖包

我们用tidyverse系列包完成数据处理和绘图,先安装加载:

# 首次使用先安装
install.packages("tidyverse")
# 加载包
library(tidyverse)

2. 批量重构数据

你原代码是逐个处理题目,效率偏低,我们直接批量处理所有Q7系列题目,转成长表格式适配绘图需求:

# 提取所有Q7相关列,替换-99为缺失值
plot_data <- data %>%
  select(starts_with("Q7")) %>%
  mutate(across(everything(), ~ifelse(. == -99, NA, .))) %>%
  # 宽表转长表
  pivot_longer(everything(), names_to = "question", values_to = "answer") %>%
  # 去掉缺失值
  filter(!is.na(answer)) %>%
  # 因子化答案,保证顺序和你设定的一致
  mutate(answer = factor(answer,
                         levels = 1:5, # 假设原始答案编码是1到5对应五个选项,可根据实际调整
                         labels = c("Strongly Disagree", "Disagree", "Neither Agree nor Disagree", "Agree", "Strongly Agree")))

3. 分组计算百分比

按题目分组,计算每个选项的占比:

percent_data <- plot_data %>%
  group_by(question, answer) %>%
  summarise(count = n()) %>%
  mutate(percentage = count / sum(count) * 100) %>%
  ungroup()

4. 绘制100%堆叠条形图

ggplot(percent_data, aes(x = question, y = percentage, fill = answer)) +
  # 堆叠柱形,position="fill"自动按100%比例展示
  geom_col(position = "fill", color = "white") +
  # y轴转为百分比格式
  scale_y_continuous(labels = scales::percent_format()) +
  # 调整配色,可根据需要替换为自定义色值
  scale_fill_brewer(palette = "RdYlBu", direction = -1) +
  # 添加百分比标签
  geom_text(aes(label = paste0(round(percentage, 1), "%")), 
            position = position_fill(vjust = 0.5), size = 3.5) +
  # 调整坐标轴和标题
  labs(x = "调查问题", y = "占比", fill = "同意程度",
       title = "各问题同意程度分布") +
  # 调整主题,翻转坐标更符合常见问卷结果展示样式(可选)
  coord_flip() +
  theme_minimal() +
  theme(legend.position = "bottom")

如果你需要把x轴的Q7_1、Q7_2替换为实际的问题描述,只需给percent_data$question做因子化,设置对应labels即可。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:36:03