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

如何用ggplot绘制以Month为X轴、双计数变量为填充的堆叠聚类条形图

问题:使用ggplot创建堆叠聚类条形图

需求:制作以Month为X轴,将HAPI和Admissions两个计数变量作为填充的堆叠聚类条形图,目标效果为两类计数在条形中堆叠展示的分组图表。

核心问题:HAPI和Admissions均为计数变量而非分类变量,现有代码仅能将HAPI设为填充维度,无法实现两类计数的堆叠展示,不符合预期效果。

示例数据代码

df <- data.frame(
  Group = c("Pre", "Pre", "Pre", "Pre", "Pre", "Pre", "Post", "Post", "Post", "Post", 
            "Pre", "Pre", "Pre", "Pre", "Pre", "Pre", "Post", "Post", "Post", "Post"),
  Month = c("Jan", "Feb", "March", "Apr", "May", "June", "June", "July", "Aug", "Sept", 
            "Jan", "Feb", "March", "Apr", "May", "June", "June", "July", "Aug", "Sept"),
  Unit = c(100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200),
  HAPI = c(0, 1, 0, 6, 1, 2, 0, 0, 0, 1, 0, 0, 6, 0, 3, 0, 0, 0, 0, 0),
  Admissions = c(83, 77, 79, 114, 101, 20, 62, 96, 92, 64, 84, 74, 92, 130, 90, 15, 44, 82, 79, 83)
)

现有代码

ggplot(df, aes(x = Month, y = Admissions, fill = HAPI)) + 
  geom_bar(stat = "identity", position = "stack") +
  facet_grid(~ Group) + 
  theme_minimal() + 
  labs(x='Month') 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:45:32