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

R语言ggplot2堆叠条形图按指定类别值重排条形顺序方法

解决方案

排序不生效的核心原因是:Identity默认是字符型,ggplot会自动按字母顺序排列x轴类别;之前尝试的fct_reorder写法没指定仅取FavorableLevel == "High"对应的Value作为排序依据,把三个层级的数值混在一起计算,结果自然不符合预期。


完整可运行代码

需要用到tidyverse套件(包含ggplot2和处理因子的forcats包,未安装的话先运行install.packages("tidyverse")):

library(tidyverse)

data1 %>%
  mutate(
    # 固定堆叠层级顺序:从下到上为Low/Medium/High
    FavorableLevel = factor(FavorableLevel, levels = c("Low", "Medium", "High")),
    # 核心逻辑:重排Identity因子顺序,按High对应的Value升序排列
    Identity = fct_reorder(
      .f = Identity,
      .x = Value,
      .fun = function(val) val[cur_data()$FavorableLevel == "High"]
    )
  ) %>%
  ggplot(aes(x = Identity, y = Value, fill = FavorableLevel)) +
  geom_bar(position = "fill", stat = "identity")

效果核对

手动提取每个Identity对应High层级的Value,升序结果如下:

  • Orange:0.11
  • Red:0.18
  • Green:0.27
  • Blue:0.28
  • Yellow:0.45
    运行代码后x轴从左到右会严格按照这个顺序排列,完全符合要求。

简易替代方案

如果类别数量少、不需要动态排序,也可以手动指定因子水平,效果完全一致:

# 手动指定Identity的因子顺序
data1$Identity <- factor(
  data1$Identity,
  levels = c("Orange", "Red", "Green", "Blue", "Yellow")
)

# 后续直接运行原有绘图代码即可
ggplot(data1, 
   aes(fill=factor(FavorableLevel, levels = c("Low","Medium","High")), 
       y=Value, 
       x=Identity)) + 
geom_bar(position="fill", stat="identity")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 19:48:34