我试图用数据制作一个类似于下面的堆叠条形图:
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')))
有谁知道如何用这种方法来分离或分解两列?
任何建议都非常感谢!!
1条答案
按热度按时间b4wnujal1#
ggplot2提供了几种将数据Map到水平位置的方法:面、x轴和匀光,通过
position_dodge
。我们也可以用position_stack
来堆叠条形图,这与多个组的geom_col
一起隐式使用。但是没有组合的减淡+堆叠位置计算,所以如果我们想要一个在水平轴上有三个划分级别的堆叠柱形图,一种方法是手动计算垂直位置,并依靠
position_dodge()
进行水平定位。(此处添加了
geom_text
层,以证明条形图的大小正确。)