I have the following data frame
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()
I would like to overlay the density plot to the histogram, but it just appears like a thin line in 0
You'll need to get geom_histogram
and geom_density
to share the same axis. In this case, I've specified both to plot against density by adding the aes(y=..density)
term to geom_histogram
. Note also some different aesthetics to avoid overplotting and so that we are able to see both geoms a bit more clearly:
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)
As initially specified, the aesthetics fill=
applies to both, so you have the histogram and density geoms showing you distribution grouped according to "x1" and "x2". If you want the density geom for the combined set of x1 and x2, just specify the fill=
aesthetic for the histogram geom only:
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)
But I would like the density of the whole distribution, not grouped
Use
geom_density(alpha=0)
for a better view.@AdriánVallsCarbó - see the adjustment in the answer. You should specify the
fill=
aesthetic within the specific geom. In the example, I've moved it so that the histogram geom is showing distributions for x1 and x2, whereas the density geom shows for the whole distribution of x.