我有以下数据框
x1<-data.frame(n = rnorm(1000000, mean=0, sd=1), nombre= "x1")
x2<-data.frame(n=rnorm(1500000, mean=3, sd=1), nombre= "x2")
x<-rbind(x1, x2)
ggplot(x, aes(n, fill=nombre))+
geom_histogram(alpha=0.5, binwidth=0.25, position = "identity")+
geom_density()
我想将密度图叠加到直方图上,但它看起来像 0 中的一条细线
最佳答案
您需要获取 geom_histogram
和 geom_density
共享同一轴。在这种情况下,我通过添加 aes(y=..density)
指定两者都针对密度进行绘图。期限到 geom_histogram
.还要注意一些不同的美学,以避免过度绘制,以便我们能够更清楚地看到两个几何体:
ggplot(x, aes(n, fill=nombre))+
geom_histogram(aes(y=..density..), color='gray50',
alpha=0.2, binwidth=0.25, position = "identity")+
geom_density(alpha=0.2)
正如最初指定的那样,美学
fill=
适用于两者,所以你有直方图和密度几何显示你根据“x1”和“x2”分组的分布。如果您想要 x1 和 x2 组合集的密度几何,只需指定 fill=
仅直方图几何的美学:ggplot(x, aes(n))+
geom_histogram(aes(y=..density.., fill=nombre),
color='gray50', alpha=0.2,
binwidth=0.25, position = "identity")+
geom_density(alpha=0.2)
关于r - ggplot2 中的密度图和直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61548507/