ggplot2中具有单独权重的多个密度

时间:2016-07-15 21:52:42

标签: r ggplot2

R中,我想使用权重x按组y绘制数据框列w的内核密度。

我的问题是加权是在所有数据上完成的,而不是按组完成的。这导致“权重总和<1”错误。

这是一个MWE:

n = 10000
df <- data.frame(x = rnorm(n), y = rbinom(n,1,prob=0.25), w = exp(rnorm(n)))

# Make density plots by y, weighted by w
ggplot(df,aes(x=x,group=y)) + geom_density(aes(weights=w/sum(w)))

enter image description here

正如您所看到的,这些密度都没有整合到一个密度中。

如何让小组完成加权?

0 个答案:

没有答案