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

如何在R的ggplot2堆叠条形图中对堆叠项进行降序排序?

解决堆叠条形图排序问题

要实现堆叠条形图按指定维度降序排序,核心是让坐标轴类别(因使用coord_flip,实际对应y轴)根据堆叠中某一部分的数值排序,以下是具体修改方案:

方案1:在ggplot中直接指定排序依据

修改ggplot的x轴映射,以**"Yes"类别的百分比降序**为例,将原代码中的x = variable替换为x = reorder(variable, -value * (Decision == "Yes"))。这里(Decision == "Yes")会生成逻辑值,对应"Yes"时为1、"No"时为0,与value相乘后仅保留"Yes"的数值,加负号实现降序排列。

修改后的完整代码:

adopt <- data.frame(
  Decision = c("No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes", "No", "Yes"),
  variable = c("Cereals", "Cereals", "Forage", "Forage", "Fruit tree", "Fruit tree", "Horticulture", "Horticulture", "Industrial", 
              "Industrial", "Legume", "Legume", "Root crop", "Root crop", "Other", "Other", "Total", "Total"),
  value = c(35.59,64.41,22.76,77.24,26.28,73.72,27.8,72.2,20.52,79.48,35.64,64.36,32.89,67.11,19.38,80.63,30.52,69.48)
)

library(ggplot2)

##Vertical/Hor adoption graph##
ggplot(adopt, aes(fill = Decision, y = value, x = reorder(variable, -value * (Decision == "Yes")))) +
  geom_bar(stat = "identity", position = "stack")+
  ylab("Percentage of Farmers")+
  xlab("Types of farm")+
  coord_flip()+
  theme_classic()+
  scale_fill_brewer(palette = "Blues", direction = 1)+
  scale_y_continuous(labels = scales::label_percent(scale = 1, accuracy = 1))+
  theme(legend.text = element_text(size = 15))+
  theme(legend.title = element_text(size = 17))+
  theme(axis.text.y = element_text(size=14))+
  theme(axis.text.x = element_text(size=13, angle = 0))+
  theme(axis.title = element_text(size = 17))+
  theme(plot.title = element_text(size=22, hjust=0.5))+
  theme(text = element_text(size=16, family="Times New Roman"))

方案2:预处理数据,手动设置因子顺序

若需要更直观的排序控制,可以先提取每个类别对应的目标排序值,再将variable转换为有序因子:

# 提取每个variable的"Yes"占比并按降序排列,得到排序顺序
sort_order <- adopt[adopt$Decision == "Yes", ] %>% 
  arrange(desc(value)) %>% 
  pull(variable)

# 将variable转换为有序因子,顺序按sort_order设定
adopt$variable <- factor(adopt$variable, levels = sort_order)

# 后续ggplot代码无需修改x轴映射,直接使用x = variable即可
ggplot(adopt, aes(fill = Decision, y = value, x = variable)) +
  # 其余代码与原代码一致

额外说明

  • 原代码中修改levels的语句是多余的,你的variable列本来就是正确的字符值,无需额外调整因子水平,可直接删除。
  • 若要按"No"的占比排序,只需将方案1中的(Decision == "Yes")改为(Decision == "No"),或方案2中提取Decision == "No"的数据即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:15:09