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

R语言Likert包分组100%堆叠条形图X轴反转问题求助

Likert包分组100%堆叠条形图方向反转问题解决

问题现象

使用R语言likert包处理李克特量表数据时:

  • 未分组的100%堆叠条形图(设置centered=FALSE)显示正常,低李克特值在左侧、高值在右侧
  • 分组的100%堆叠条形图(centered=FALSE)出现异常:低分值在右侧、高分值在左侧,中性百分比未对齐,与分组发散条形图(centered=TRUE)的方向完全相反
  • 尝试调整likert.options参数无法解决该问题,期望条形方向与发散图一致(低左高右)

复现代码如下:

library(likert)
library(tidyverse)

n <- 3000

set.seed(123)

# 数据集:Q1a/b/c为李克特变量(水平1-5,3为中性),group为分组变量
some_made_up_data <- data.frame(
  Q1a = as.factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.03,.07,.2,.4, .3))),
  Q1b = as.factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.02,.1,.2,.3, .3))),
  Q1c = as.factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.05,.2,.2,.4, .2))),
  group = as.factor(sample(c("g1", "g2", "g3", "g4", "g5"), n, replace = TRUE))
)

# 未分组100%堆叠条形图(正常)
L1<-likert(some_made_up_data[,-4]) %>% 
  plot(type="bar", centered=F)

# 分组发散条形图(方向正确)
L2<-likert(some_made_up_data[,1,drop=FALSE],grouping = some_made_up_data$group) %>% 
  plot(type="bar", centered=T)

# 分组100%堆叠条形图(存在方向反转问题)
L3<-likert(some_made_up_data[,1,drop=FALSE],grouping = some_made_up_data$group) %>% 
  plot(type="bar", centered=F)

# 查看图表
L1
L2
L3

解决方案

问题根源是likert包在绘制分组堆叠条形图时,默认反转了李克特水平的堆叠顺序。可以通过以下两种方法修正:

方法一:修改ggplot输出的堆叠方向

直接在生成的ggplot对象中调整堆叠方向,并确保填充顺序与李克特水平一致:

# 修正后的分组100%堆叠条形图
L3_fixed <- likert(some_made_up_data[,1,drop=FALSE], grouping = some_made_up_data$group) %>% 
  plot(type="bar", centered=F) +
  # 反转堆叠顺序,让低分值在左
  geom_bar(position = position_stack(reverse = TRUE)) +
  # 确保填充颜色的顺序与李克特水平匹配
  scale_fill_discrete(limits = levels(some_made_up_data$Q1a))

# 查看修正后的图
L3_fixed

方法二:提前设置有序因子

在创建数据集时,将李克特变量定义为有序因子,明确指定水平从低到高的顺序,让likert包默认按正确方向绘制:

# 重新创建带有序因子的数据集
set.seed(123)
some_made_up_data_ordered <- data.frame(
  Q1a = factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.03,.07,.2,.4, .3)),
               levels = c("1","2","3","4","5"), ordered = TRUE),
  Q1b = factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.02,.1,.2,.3, .3)),
               levels = c("1","2","3","4","5"), ordered = TRUE),
  Q1c = factor(sample(c(1,2,3,4,5), n, replace = TRUE, prob = c(.05,.2,.2,.4, .2)),
               levels = c("1","2","3","4","5"), ordered = TRUE),
  group = as.factor(sample(c("g1", "g2", "g3", "g4", "g5"), n, replace = TRUE))
)

# 绘制分组堆叠图
L3_fixed2 <- likert(some_made_up_data_ordered[,1,drop=FALSE], grouping = some_made_up_data_ordered$group) %>% 
  plot(type="bar", centered=F)

# 查看图
L3_fixed2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:35:27