[英]How to avoid a flat density line in ggplot2
I'm trying to plot a density line over 2 overlapped histograms, but with every code I use, the line gets "flat".我正在尝试 plot 一条超过 2 个重叠直方图的密度线,但是对于我使用的每个代码,这条线都会变得“平坦”。
I have to create two histograms, each with a normal distribution, and a different number of samples.我必须创建两个直方图,每个直方图都具有正态分布和不同数量的样本。 Then I have to overlap both and write the density line.
然后我必须将两者重叠并写下密度线。 All with ggplot2 package.
全部采用 ggplot2 package。
This is what I've tried:这是我尝试过的:
xx<-data.frame(dat = rnorm(n, mean, sd))
yy<-data.frame(dat = rnorm(n, mean, sd))
both<-rbind(xx, yy)
ggplot(both, aes(x=dat)) +
geom_histogram(data = xx, fill = "red", alpha = 0.2,binwidth=0.25) +
geom_histogram(data = yy, fill = "blue", alpha = 0.2, binwidth=0.25) +
theme_light() +
geom_line(data=samples, stat = "density")
I also tried geom_density
but the result is the same...我也试过
geom_density
但结果是一样的......
The density line is not flat, it's simply on a very different scale with respect to the histograms, since, by default, the histogram is created using counts on the y-axis.密度线不是平坦的,它只是相对于直方图的一个非常不同的比例,因为默认情况下,直方图是使用 y 轴上的计数创建的。
You should specify y = after_stat(density)
:您应该指定
y = after_stat(density)
:
# packages
library(ggplot2)
# data
set.seed(1)
sample1 <- data.frame(dat = rnorm(10000, 0, 1))
sample2 <- data.frame(dat = rnorm(15000, 3, 1))
both <- rbind(sample1, sample2)
ggplot(both, aes(x = dat)) +
geom_histogram(aes(y = after_stat(density)), data = sample1, fill = "red", alpha = 0.2, binwidth = 0.25) +
geom_histogram(aes(y = after_stat(density)), data = sample2, fill = "blue", alpha = 0.2, binwidth=0.25) +
theme_light() +
geom_line(stat = "density")
Created on 2020-04-30 by the reprex package (v0.3.0)由代表 package (v0.3.0) 于 2020 年 4 月 30 日创建
The black line represents a sort of a mixture of the two normal distributions.黑线代表两种正态分布的混合。 You should read the help page of the
after_stat
function for more details.您应该阅读
after_stat
function 的帮助页面以了解更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.