如何使用ggplot2中的填充美学绘制两个组的相对比例?
我在这里问这个问题是因为关于此主题的其他几个答案似乎不正确(ex1,ex2和ex3),但“交叉验证”似乎在功能上禁止了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)
似乎产生正确输出的答案是不使用ggplot2的解决方案(在ggplot2之外进行计算)或要求使用面板而不是填充外观。
编辑:挖掘stat_bin会产生最终调用的函数是bin,但是bin仅传递x aes中的值。而无需重写stat_bin(或使得另一stat_),其在上述参考答案施加可以推广到填充AES黑客在不存在组AES的与Y AES以下代码:y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x]))
。这只是将PANEL(位于StatBin末尾的隐藏列)替换为fill)。大概其他隐藏变量也可以得到相同的处理。
这是一个很棒的技巧,但它似乎可以完成您想要的...
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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句