5

如何在 ggplot2 中使用填充美学绘制两组的相对比例?

我在这里问这个问题是因为关于这个主题的其他几个答案似乎不正确(ex1ex2ex3),但 Cross Validated 似乎在功能上禁止了 R 特定问题(CV meta)。 ..density..在概念上与比例相关,但不同于比例(ex4ex5)。所以正确答案似乎不涉及密度。

例子:

set.seed(1200)
test <- data.frame(
  test1 = factor(sample(letters[1:2], 100, replace = TRUE,prob=c(.25,.75)),ordered=TRUE,levels=letters[1:2]), 
  test2 = factor(sample(letters[3:8], 100, replace = TRUE),ordered=TRUE,levels=letters[3:8])
)
ggplot(test, aes(test2)) + geom_bar(aes(y = ..density.., group=test1, fill=test1) ,position="dodge")
#For example, the plotted data shows level a x c as being slightly in excess of .15, but a manual calculation shows a value of .138
counts <- with(test,table(test1,test2))
counts/matrix(rowSums(counts),nrow=2,ncol=6)

似乎产生正确输出的答案求助于不使用 ggplot2(在 ggplot2 之外计算)或要求使用面板而不是填充美学的解决方案。

编辑:挖掘 stat_bin 得出最终调用的函数是 bin,但 bin 只传递了 x aes 中的值。在不重写 stat_bin (或制作另一个 stat_ )的情况下,在上面引用的答案中应用的 hack 可以在没有组 aes 的情况下推广到填充 aes,并为 y aes 使用以下代码:y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x]))。这只是用填充替换了 PANEL(StatBin 末尾的隐藏列)。据推测,其他隐藏变量可以得到相同的处理。

4

1 回答 1

5

这是一个很棒的黑客,但它似乎可以做你想做的事......

ggplot(test, aes(test2)) + geom_bar(aes(y = ..count../rep(c(sum(..count..[1:6]), sum(..count..[7:12])), each=6), 
                                    group=test1, fill=test1) ,position="dodge") + 
                                      scale_y_continuous(name="proportion")
于 2013-07-15T14:32:18.127 回答