【问题标题】:How to draw a stacked barplot with three categorical variables representing the proportion of only one of them for each facet in r?如何绘制一个堆叠的条形图,其中三个分类变量代表 r 中每个方面仅其中一个的比例?
【发布时间】:2020-06-01 17:21:19
【问题描述】:

这是作为参考的数据

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 比例而不是绝对值?

谢谢!

【问题讨论】:

  • 您是否尝试过构建一个比例变量,然后在绘图中使用它?
  • 是的,我考虑过这一点,但是由于我主要使用具有大量变量的 igraph 对象并且我需要一个简单的代码,我想知道是否有解决方案可以保持 df 原样.事实证明,多亏了伊恩的回应,这是可能的。

标签: r ggplot2 stack bar-chart prop


【解决方案1】:

这是一种使用..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 是类数字,因此您需要将其转换为因子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多