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

如何创建外层组内子组并列的堆叠条形图?

问题:实现堆叠分组的对比图表

我希望创建包含堆叠分组效果的3组数据对比图表,但当前代码会将group也进行堆叠。期望的效果是:每个id下分为groupA、groupB、groupC三个独立分组,每个分组内部对应type进行堆叠展示。

示例数据集

df <- data.frame(
  id = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3),
  value = c(3, 4, 1, 2, 2, 3, 2, 1, 3, 1, 7, 8, 7, 8),
  type = c("a1", "b1", "c1", "c2", "a1", "a2", "b1", "b2", "b1", "b2", "c1", "a1", "a2", "a3"),
  group = c("groupA", "groupB", "groupC", "groupC", "groupA", "groupA", "groupB", "groupB", "groupB", "groupB", "groupC", "groupA", "groupB", "groupC")
)

当前使用的代码

ggplot(df, aes(fill = type, x = id, y = value, group = group)) +
  geom_col() +
  scale_fill_manual(values = c("a1" = "#00acee", "a2" = "#3e89ac", "b1" = "#f4821e", "b2" = "#c36818", "c1" = "#49cd83", "c2" = "#169a50")) +
  theme_classic()

当前问题

运行上述代码后,同一id下的所有type会被堆叠在一起,没有区分group分组,无法实现“分组并排+组内堆叠”的效果。

解决方案

有两种常用方法可以实现目标效果:

方法一:使用position_dodge()实现同一id下分组并排

通过指定分组逻辑和位置调整参数,让不同group的柱子在同一id下并排,同时保留组内type的堆叠:

library(ggplot2)

ggplot(df, aes(x = id, y = value, fill = type, group = group)) +
  geom_col(position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c(
    "a1" = "#00acee", "a2" = "#3e89ac", "a3" = "#0077b6",
    "b1" = "#f4821e", "b2" = "#c36818",
    "c1" = "#49cd83", "c2" = "#169a50"
  )) +
  theme_classic()

方法二:将id与group组合作为x轴项

把id和group的组合作为x轴的独立元素,每个元素内部实现type的堆叠,直观区分分组结构:

library(ggplot2)
library(stringr)

ggplot(df, aes(x = interaction(id, group), y = value, fill = type)) +
  geom_col() +
  # 调整x轴标签,换行显示id和group
  scale_x_discrete(labels = function(x) str_replace(x, "\\.", "\n")) +
  scale_fill_manual(values = c(
    "a1" = "#00acee", "a2" = "#3e89ac", "a3" = "#0077b6",
    "b1" = "#f4821e", "b2" = "#c36818",
    "c1" = "#49cd83", "c2" = "#169a50"
  )) +
  theme_classic()

关键说明

  • 两种方法都补充了原代码中缺失的a3颜色值,确保所有type都有对应的填充色。
  • 方法一适合保持x轴为id的场景,方法二更清晰展示每个id下的分组结构。

内容的提问来源于stack exchange,提问作者Yuto Best boy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:34:50