如何绘制具有三个分类变量的堆叠条形图,代表 r 中每个方面仅其中一个的比例?

How to draw a stacked barplot with three categorical variables representing the proportion of only one of them for each facet in r?

此为参考数据

df <- data.frame(a = c(3,3,3,3,3,2,2,3,2,1,1,1,3,1,3), b = c(1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2), c = c(4, 5, 3, 2, 4, 2, 3, 4, 5, 4, 4, 3, 3, 1, 2) )

我想绘制一个条形图,其中每个面的比例为 a。同时我希望根据 b 值对条形图进行着色。 变量 b 与计算百分比无关。这是我想出来的,当我设置fill = c时,它将堆叠的颜色分成两部分,一个对应1,另一个对应NA。

      ggplot(aes(x = a, y = ...prop..., group = 1, fill = b)) +
          geom_bar(position = "stack") +
          facet_wrap(~c, nrow = 1, ncol = 5) +
          labs(title = "Count of a among c")

我怎样才能得到类似于这个的结果,但每个刻面环绕的比例是 a 的比例而不是绝对值?

谢谢!

这是使用 ..count....PANEL.. 特殊符号的方法:

ggplot(df, aes(x = a, fill = as.factor(b))) +
  geom_bar(aes(y = ..count.. / tapply(..count..,..PANEL..,sum)[..PANEL..])) +
  facet_wrap(~c, nrow = 1, ncol = 5) +
  labs(title = "Count of a among c", fill = "b", y = "Proportion")  

如果您不使用 facet_wrap,那么设置 y = ..prop.. 就很简单了。但是, ..prop.. 未按方面正确计算。所以,为了解决这个问题,我们可以只对那个面板使用 tapply..PANEL..sum ..count.. 的特殊符号。最后的[..PANEL..]是对结果向量进行子集化。

您遇到的另一个问题是 b 是 class 数字,因此您需要将其转换为因子。