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

ggplot2堆叠柱状图调整:NA堆叠设灰色+total列移至右端

解决方案

针对你的两个需求,可通过以下步骤修改代码实现:

1. 将值为"NA"的堆叠设为灰色

调整fill的映射逻辑,把ig列中值为"NA"的条目单独归为一组,手动指定该组的填充色为灰色。

2. 将"total"列移至右端

把ejes列转换为因子类型,指定因子水平顺序时将"total"放在最后——因coord_flip()翻转了坐标轴,原y轴的堆叠顺序对应翻转后的x轴左右位置,这样"total"会出现在每个条形的最右端。

修改后的完整代码

# 加载必要包
library(ggplot2)

# 原始数据集
institucion <- data.frame( 
               inst = c(rep("Inst1", 6), rep("Inst2", 6), rep("Inst3", 6), rep("Inst4", 6), rep("Inst5", 6)), 
               ejes = rep(c("total", "eje 1", "eje 2", "eje 3", "eje 4", "eje 5"), 5), 
               ig = c(1, "NA", "NA", "NA", "NA", "Total: 1", 1, 2, "NA", 4, 5,  "Total: 12", 1 , 2, 3, "NA", 5,  "Total: 11",
                      1, "NA", "NA", 4, 5, "Total: 10", 1, "NA", 3, 4, 5, "Total: 13"),   
               peso = rep(100/6, 30) 
)

# 预处理:调整ejes的因子顺序,将total放在最后
institucion$ejes <- factor(institucion$ejes, levels = c("eje 1", "eje 2", "eje 3", "eje 4", "eje 5", "total"))

# 绘制堆叠柱状图
plot6 <- ggplot(institucion, aes(x = inst, y = peso, 
                                 fill = ifelse(ig == "NA", "NA_val", ejes), 
                                 label = ig)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  geom_text(aes(label = ig), position = position_stack(vjust = 0.5)) +
  scale_fill_manual(values = c(
    "eje 1" = "blue", 
    "eje 2" = "red", 
    "eje 3" = "darkgreen", 
    "eje 4" = "pink", 
    "eje 5" = "purple", 
    "total" = "white", 
    "NA_val" = "gray"
  )) +
  theme(legend.title = element_blank(), rect = element_blank())

# 查看图形
print(plot6)

关键修改说明

  • 因子水平调整:通过factor()重新定义ejes的顺序,确保堆叠时"total"处于最右端。
  • 填充色逻辑:用ifelse()把所有"NA"条目单独分组,后续通过scale_fill_manual给该组指定灰色,其余类别保留原配色。
  • 配色精简:移除原代码中多余的颜色值,只保留需要的类别对应颜色,避免逻辑混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:25:32