如何在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之外计算它)的解决方案,或者需要使用面板而不是填充美学. …