R 如何避免ggplot2中出现平坦的密度线
我试图在两个重叠的直方图上绘制一条密度线,但在我使用的每一个代码中,这条线都变得“平坦” 我必须创建两个直方图,每个直方图具有正态分布,并且样本数量不同。然后我必须重叠这两条线,然后写密度线。全部带有ggplot2软件包 这就是我尝试过的:R 如何避免ggplot2中出现平坦的密度线,r,ggplot2,histogram,kernel-density,density-plot,R,Ggplot2,Histogram,Kernel Density,Density Plot,我试图在两个重叠的直方图上绘制一条密度线,但在我使用的每一个代码中,这条线都变得“平坦” 我必须创建两个直方图,每个直方图具有正态分布,并且样本数量不同。然后我必须重叠这两条线,然后写密度线。全部带有ggplot2软件包 这就是我尝试过的: xx<-data.frame(dat = rnorm(n, mean, sd)) yy<-data.frame(dat = rnorm(n, mean, sd)) both<-rbind(xx, yy) ggplot(both, aes(
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")
xx密度线不是平坦的,它与直方图的比例非常不同,因为默认情况下,直方图是使用y轴上的计数创建的
您应该在统计(密度)之后指定y=
#包
图书馆(GG2)
#资料
种子(1)
示例1请编辑问题以包含一些示例数据(您可以使用dput(示例1)
)。最好的策略可能是将sample1和sample2与dplyr::bind_rows
相结合,并将fill
添加到aes
中。我得到一个错误,在after_stat(density)中说错误:无法找到函数“after_stat”
尽管库(ggplot2)
被激活函数after_stat()
是在ggplot2
的3.3.0版中引入的(请参见此处新功能部分的第一个要点:)。如果可以,我认为应该更新包,否则可以使用较旧的方法,即y=stat(density)
或y=…density.
。