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

ggplot2堆叠柱状图搭配帕累托线时geom_text()标签顺序颠倒求助

问题原因

堆叠柱状图的geom_text标签顺序颠倒,核心是geom_text未声明与geom_bar一致的分组映射,导致堆叠计算时的组排序和柱子实际堆叠顺序不匹配。

解决方法

  1. 优先补全geom_text的分组映射,在aes中加入和geom_bar一致的fill = alvor参数,让文本知道按对应分组堆叠:
ggplot() +
  theme_mso() +
  geom_bar(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor), stat = "identity") +
  # 补全fill=alvor映射
  geom_text(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor, label = n), position = position_stack(vjust = .5)) +
  scale_fill_manual(values = col) +
  geom_point(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret)) +
  geom_line(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, group = 1), stat = "identity") +
  scale_y_continuous(sec.axis = sec_axis(~(./total_value)*100, name = "Procent")) +
  geom_text(data = uth.sum2, aes(x = dpsd_ny, y = akkumuleret, label = procent), position = position_stack(vjust= 1.08))
  1. 如果补全映射后标签仍然颠倒,给position_stack添加reverse = TRUE参数手动对齐顺序:
geom_text(data = uth.sum, aes(x = reorder(dpsd_ny, -n), y = n, fill = alvor, label = n), position = position_stack(vjust = .5, reverse = TRUE))
  1. 若要从根源避免顺序错乱,可主动指定fill变量的因子顺序,明确堆叠逻辑:
# 按你需要的从下到上的堆叠顺序设置levels
uth.sum$alvor <- factor(uth.sum$alvor, levels = c("最低层类别", "中间层类别", "最高层类别"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:48:03