R语言 如何使用ggplot2在x轴上获得每个值两个条形图?

e5nqia27  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(140)

我试图用数据制作一个类似于下面的堆叠条形图:

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",
)

我想在x轴上显示Date,在y轴上显示Count,但我还想用Test_Type * 和 * Test_Target分隔,得到如下所示的结果:

但我能得到的最接近的结果是这样的,它结合了/的计数,并没有区分Test_Target

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

有谁知道如何用这种方法来分离或分解两列?
任何建议都非常感谢!!

b4wnujal

b4wnujal1#

ggplot2提供了几种将数据Map到水平位置的方法:面、x轴和匀光,通过position_dodge。我们也可以用position_stack来堆叠条形图,这与多个组的geom_col一起隐式使用。
但是没有组合的减淡+堆叠位置计算,所以如果我们想要一个在水平轴上有三个划分级别的堆叠柱形图,一种方法是手动计算垂直位置,并依靠position_dodge()进行水平定位。
(此处添加了geom_text层,以证明条形图的大小正确。)

library(dplyr); library(ggplot2)
df %>%
  mutate(mid = cumsum(Count) - Count/2, .by = c(Date, Test_Target, Test_Type)) %>%
  ggplot(aes(Date, mid, height = Count, width = 0.8, fill = Outcome, group = Test_Target)) +
  geom_tile(position = position_dodge(width = 0.85)) +
  geom_text(aes(label = Count), position = position_dodge(width = 0.85)) +
  facet_wrap(~Test_Type)

相关问题