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

如何用ggplot2在X轴每个值旁生成两组堆叠柱状图?

实现按Test_Type和Test_Target分组的堆叠柱状图

问题背景

需要绘制堆叠柱状图:X轴为Date,Y轴为Count,按Outcome堆叠,同时要区分Test_Type和Test_Target的组合分组。现有代码仅通过facet_grid拆分Test_Type,无法体现Test_Target的维度。

数据集

df <- tribble(
  ~Count, ~Date, ~Test_Type, ~Test_Target, ~Outcome,
  8, "Fall", "A", "H5", "Positive",
  7, "Fall", "A", "H5", "Negative",
  10, "Fall", "A", "H5", "Inconclusive",
  6, "Fall", "A", "H7", "Positive",
  11, "Fall", "A", "H7", "Negative",
  0, "Fall", "A", "H7", "Inconclusive",
  12, "Fall", "B", "H5", "Positive",
  6, "Fall", "B", "H5", "Negative",
  3, "Fall", "B", "H5", "Inconclusive",
  0, "Fall", "B", "H7", "Positive",
  7, "Fall", "B", "H7", "Negative",
  11, "Fall", "B", "H7", "Inconclusive",
  9, "Winter", "A", "H5", "Positive",
  5, "Winter", "A", "H5", "Negative",
  4, "Winter", "A", "H5", "Inconclusive",
  0, "Winter", "A", "H7", "Positive",
  13, "Winter", "A", "H7", "Negative",
  14, "Winter", "A", "H7", "Inconclusive",
  2, "Winter", "B", "H5", "Positive",
  1, "Winter", "B", "H5", "Negative",
  6, "Winter", "B", "H5", "Inconclusive",
  9, "Winter", "B", "H7", "Positive",
  17, "Winter", "B", "H7", "Negative",
  0, "Winter", "B", "H7", "Inconclusive",
)

现有代码

df %>% ggplot(aes(x = Date, fill = Outcome, y = Count)) +
  geom_col() +
  facet_grid(~factor(Test_Type, levels = c('A', 'B')))

解决方案

提供两种常用实现方式,可根据可视化需求选择:

方式1:用facet_grid拆分双维度

将Test_Type和Test_Target分别作为分面的列和行,清晰展示所有组合分组的堆叠情况:

library(ggplot2)
library(tibble)

df %>% 
  ggplot(aes(x = Date, fill = Outcome, y = Count)) +
  geom_col(position = "stack") +
  facet_grid(Test_Target ~ factor(Test_Type, levels = c('A', 'B'))) +
  labs(title = "堆叠柱状图:按检测类型与目标分组",
       x = "季节", y = "数量", fill = "检测结果") +
  theme_minimal()

这种方式生成网格状子图,行对应Test_Target(H5/H7),列对应Test_Type(A/B),每个子图独立展示对应分组下的季节-结果堆叠分布。

方式2:合并分组变量后展示

将Test_Type和Test_Target合并为一个新变量,通过分面或X轴分组呈现:

# 合并变量后用facet_wrap拆分
df %>% 
  mutate(Group = paste(Test_Type, Test_Target, sep = "-")) %>%
  ggplot(aes(x = Date, fill = Outcome, y = Count)) +
  geom_col() +
  facet_wrap(~Group) +
  labs(title = "堆叠柱状图:合并检测类型与目标分组",
       x = "季节", y = "数量", fill = "检测结果") +
  theme_minimal()

# 或直接将合并变量与Date绑定为X轴
df %>% 
  mutate(Group = paste(Test_Type, Test_Target, sep = "-")) %>%
  ggplot(aes(x = interaction(Date, Group), fill = Outcome, y = Count)) +
  geom_col() +
  labs(title = "堆叠柱状图:季节-分组联合展示",
       x = "季节-检测组合", y = "数量", fill = "检测结果") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

这种方式更适合需要在同一视图下对比所有分组组合的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:37:03