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

geom_col标签顺序异常:已正确设置因子水平但未生效

解决ggplot2发散条形图标签顺序错误问题

你在使用ggplot2绘制李克特/发散条形图时,已通过因子水平设置了标签顺序,但geom_col生成的图表中标签顺序不符合预期("Bad"出现在"Not good"之前),不过图例顺序是正确的。

可复现示例代码

library(data.table)
library(ggplot2)

data = data.table::data.table(code = paste0("A", c(1,2,4,5)), 
         label = c("Very good", "Good", "Not good", "Bad"),
         pct = c(9.6, 66, -22.7, -1.7),
         group = 1)
data$label <- factor(data$label, levels = unique(data[order(code)]$label))

ggplot(data, aes(x = group, y = pct, group = label, fill = label)) +
  geom_col(width = 0.8, position = position_stack()) +
  coord_flip() 

问题原因

position_stack()默认会根据y值的大小堆叠:正数部分从下往上按数值从小到大排列,负数部分则从下往上按数值从大到小排列。你的数据中,"Not good"的pct是-22.7,"Bad"的pct是-1.7,负数堆叠时-1.7(更大)会排在-22.7上面,导致显示顺序和因子定义的[Very good, Good, Not good, Bad]相反。

解决方案

只需在position_stack()中添加reverse = TRUE参数,反转堆叠顺序,让其与因子的水平顺序保持一致:

ggplot(data, aes(x = group, y = pct, group = label, fill = label)) +
  geom_col(width = 0.8, position = position_stack(reverse = TRUE)) +
  coord_flip() 

这样修改后,图表中的标签顺序就会和你定义的因子水平顺序一致,同时图例顺序也不会受到影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:40:33