首页 > 解决方案 > 在 ggplot 条形图中按组标准化

问题描述

我遇到了与此问题中描述的相同的问题:ggplot 中的标准化条形高度(我将其作为一个新问题发布,因为我的声誉太低而无法发表评论。)我希望蓝色条形整合到 1 和红色条形以及,我认为这是公认的答案所提供的。但这对我不起作用,因为我收到此错误:

Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..density... 
Did you map your stat in the wrong layer?

当我完全按照 vpipkt 的建议做时:

ggplot(dat, aes(x = bin, y = ..density.., group = source, fill = source)) +
geom_bar(alpha = 0.5, position = 'identity')

使用 user3396385 提供的示例数据:

set.seed(47)
BG.restricted.hs = round(runif(100, min = 47, max = 1660380))
FG.hs = round(runif(1000, min = 0, max = 1820786))

dat = data.frame(x = c(BG.restricted.hs, FG.hs), 
            source = c(rep("BG", length(BG.restricted.hs)),
            rep("FG", length(FG.hs))))
dat$bin = cut(dat$x, breaks = 200)

但是,使用..count..而不是..density..没有错误:

ggplot(dat, aes(x = bin, y = ..count.., group = source, fill = source)) +
geom_bar(alpha = 0.5, position = 'identity')

但它与原始问题中的示例存在相同的问题,整体权重计数较少的数据集不太明显。既然答案被接受了,我认为它一定在某个时候起作用了......从那时起有什么想法可能出了问题吗?如果有人能告诉我他们是否有同样的问题,我会很高兴。感谢您的任何帮助 :)

标签: rggplot2

解决方案


错误消息指出..density..不可用,因此无法映射到y美学。我认为这是因为..density..不是由geom_bar()(不再)计算的。

改用..prop..

ggplot(dat, aes(x = bin, group = source, fill = source)) +
  geom_bar(alpha = 0.5, position = 'identity', aes(y = ..prop..))

在此处输入图像描述


推荐阅读