如何在 ggplot2 中使用填充美学绘制两组的相对比例? [英] How can I plot the relative proportions of two groups using a fill aesthetic in ggplot2?

查看:26
本文介绍了如何在 ggplot2 中使用填充美学绘制两组的相对比例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I plot the relative proportions of two groups using a fill aesthetic in ggplot2?

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

I am asking this question here because several other answers on this topic seem incorrect (ex1, ex2, and ex3), but Cross Validated seems to have functionally banned R specific questions (CV meta). ..density.. is conceptually related to, but distinct from proportions (ex4 and ex5). So the correct answer does not seem to involve density.

示例:

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 之外计算)或要求使用面板而不是填充美学的解决方案.

The answer that seems to yield an output that is correct resorts to a solution that doesn't use ggplot2 (calculating it outside of ggplot2) or requires that a panel be used rather than a fill aesthetic.

编辑:深入研究 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 末尾的隐藏列).想必其他隐藏变量也可以得到同样的处理.

Edit: Digging into stat_bin yields that the function ultimately called is bin, but bin only gets passed the values in the x aes. Without rewriting stat_bin (or making another stat_) the hack that was applied in the above referenced answer can be generalized to the fill aes in the absence of the group aes with the following code for the y aes: y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x])). This just replaces PANEL (the hidden column that is present at the end of StatBin) with fill). Presumably other hidden variables could get the same treatment.

推荐答案

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

This is an aweful hack, but it seems to do what you want...

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

这篇关于如何在 ggplot2 中使用填充美学绘制两组的相对比例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆