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

如何基于堆叠段高度调整ggplot堆叠条形图的堆叠顺序

解决方案

你代码中使用的aes(order = -value)参数在新版ggplot2中已被弃用,因此无法生效,可根据你的需求选择以下两种方案调整:

方案1:全局统一堆叠顺序(所有柱子的物种堆叠顺序一致,总丰度越高的物种越靠下)

先对分类变量Var1的因子水平按总活性值重排:

library(dplyr)
full_genus_new <- full_genus_new %>%
  group_by(Var1) %>%
  mutate(total_value = sum(value)) %>%
  ungroup() %>%
  # 按总活性值降序设置因子水平,堆叠时会按因子顺序从下往上排列
  mutate(Var1 = reorder(Var1, -total_value))

重排数据后直接运行你原有的绘图代码即可实现效果。

方案2:单柱独立排序(每个患者的柱子内部单独按段大小排序,最大的段始终在最下方)

无需修改原数据,仅调整geom_bar的映射参数即可:

ggplot(full_genus_new, aes(x=as.factor(Var2), y=value, fill=Var1)) +
    # 新增group映射,按value降序排列堆叠段
    geom_bar(stat="identity", position = "fill", aes(group = desc(value))) +
    scale_x_discrete() +
    ylab("Relative Microbial Activity") +
    facet_grid(cols=vars(PEDIS), scales = "free_x", space = "free_x") +
    theme_classic() +
    scale_fill_manual(values = Cb64k) +
    scale_y_continuous(labels=percent_format()) +
    theme(legend.position = "bottom", legend.text = element_text(size=8)) +
    guides(fill=guide_legend(title="Taxa")) +
    xlab("Patient") +
    theme(legend.key.size = unit(0.5,'cm'))

注意:方案2会导致不同柱子的物种顺序不一致,图例顺序也可能和柱内顺序不匹配,如果你需要图例和柱内顺序完全对应,优先选择方案1。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:27:04