rus*_*rce 5 statistics visualization r data-visualization ggplot2
如何在ggplot2中使用填充美学来绘制两组的相对比例?
我在这里问这个问题,因为关于这个主题的其他几个答案似乎不正确(ex1,ex2和ex3),但是Cross Validated似乎在功能上禁止了R特定问题(CV meta). ..density..
在概念上与比例相关,但与比例不同(ex4和ex5).所以正确答案似乎不涉及密度.
例:
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)
Run Code Online (Sandbox Code Playgroud)
似乎产生正确输出的答案适用于不使用ggplot2(在ggplot2之外计算它)的解决方案,或者需要使用面板而不是填充美学.
编辑:挖掘stat_bin会产生最终调用的函数是bin,但bin只传递x aes中的值.在不重写stat_bin(或进行另一个stat_)的情况下,在上述引用的答案中应用的hack可以在没有组aes的情况下推广到填充aes ,其中包含以下代码:y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x]))
.这只是用填充代替PANEL(StatBin末尾的隐藏列).据推测,其他隐藏变量可以得到相同的处理.
小智 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")
Run Code Online (Sandbox Code Playgroud)