R语言带长分组标签的李克特量表问卷箱线图绘制问题
问卷李克特题可视化实现方案
- 数据基础:19行5列的宽格式tibble,每行对应1名受访者的5个李克特题作答,每列对应单题的得分结果
- 核心诉求:解决base R绘图时长题项标签无法正常显示的问题,实现ggplot2单坐标轴箱线图绘制,补充对应堆叠条形图的落地代码
示例数据集结构:
# A tibble: 19 x 5 ab_overused_nationally4 ab_overused_work4 ab_amr_problem4 ab_amr_problem_work4 ab_better_use4 <dbl> <dbl> <dbl> <dbl> <dbl> 1 4 2 4 4 5 2 4 4 4 3 4 3 5 3 4 2 5 4 3 3 4 2 5 5 5 3 5 4 5 6 5 4 5 5 5 7 4 1 5 2 5 8 5 1 4 2 5 9 4 2 4 3 5
原有base R绘图参考代码
q4 <- par(mar=c(8, 2, 1, 1)) q4 <- boxplot(np$ab_overused_nationally4, np$ab_overused_work4, np$ab_amr_problem4, np$ab_amr_problem_work4, np$ab_better_use4, ylab="Likert Scale", las=2, names=question4, main="How much do you agree with the following statements", col=(c("gold", "darkgreen")))
该方案的核心问题为:5-8个词长度的分组标签,通过手动调整par边距参数始终存在显示不全的问题。
第一步:数据格式转换
ggplot2要求长格式输入,需将当前宽表转为长表,自动匹配受访者ID与题项的对应关系,代码如下:
library(tidyr) library(dplyr) data_long <- 你的原始tibble对象 |> pivot_longer( cols = everything(), names_to = "question_item", values_to = "likert_score" )
转换后每行对应1名受访者对1个题项的作答结果,可直接用于单坐标轴的分组绘图,无需额外拆分变量。
第二步:ggplot2实现单坐标轴箱线图
针对长标签显示问题,通过标签自动换行+旋转角度的方式适配,无需手动调整全局边距参数:
library(ggplot2) library(stringr) ggplot(data_long, aes(x = question_item, y = likert_score)) + geom_boxplot(fill = c("gold", "darkgreen", "gold", "darkgreen", "gold")) + # 固定纵轴为李克特1-5分范围 scale_y_continuous(limits = c(1,5), breaks = 1:5) + # 长标签按固定宽度自动换行 scale_x_discrete( labels = function(x) str_wrap(x, width = 12) ) + theme_bw() + theme( # 旋转x轴标签角度,右对齐避免重叠 axis.text.x = element_text(angle = 45, hjust = 1, size = 10) ) + labs( title = "How much do you agree with the following statements", y = "Likert Scale", x = "" )
相比base R的par手动调边距逻辑,ggplot会自动根据标签长度预留绘图空间,不会出现标签被画布截断的问题。
第三步:李克特堆叠条形图实现路径
堆叠条形图可直观展示每个题项下不同选项的作答分布,代码如下:
# 将李克特得分转为有序因子,保证堆叠顺序符合选项逻辑 data_long <- data_long |> mutate( likert_score = factor( likert_score, levels = 1:5, labels = c("非常不同意", "不同意", "中立", "同意", "非常同意") ) ) ggplot(data_long, aes(x = question_item, fill = likert_score)) + geom_bar(position = "stack", color = "white") + scale_x_discrete( labels = function(x) str_wrap(x, width = 12) ) + scale_fill_brewer(palette = "Blues", name = "作答选项") + theme_bw() + theme( axis.text.x = element_text(angle = 45, hjust = 1, size = 10) ) + labs( title = "各题项李克特作答分布", y = "作答样本数", x = "" )
内容的提问来源于stack exchange,提问作者Petra
相关产品推荐
相关产品推荐

