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

标签 r ggplot2 statistics visualization data-visualization

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

我在这里问这个问题是因为关于这个主题的其他几个答案似乎不正确( ex1ex2ex3 ),但交叉验证似乎在功能上禁止了 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)

似乎产生输出的答案是 correct求助于不使用 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 末尾的隐藏列)。据推测,其他隐藏变量也可以得到相同的处理。

最佳答案

这是一个可怕的黑客,但它似乎做你想做的......

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

关于r - 如何在 ggplot2 中使用填充美学绘制两组的相对比例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655648/

相关文章:

r - 在 R 中查看数据表

r - 如何在 ggplot2 中显示曲线的方向?

r - 使用 Cowplot align 保持绘图间距不变

python - 将数据拟合到广义极值分布

statistics - 如何衡量企业软件市场份额?

R - 从原始数据集中下载子集

r - 使用 R Markdown 对 CSV 进行 Base64 编码

r - 将年和月 ("yyyy-mm"格式)转换为日期?

R:ggplot2,如何注释面板图每个面板上的汇总统计数据

R - 鼠标 - 添加一个列,该列对具有估算值的列求和