Warm tip: This article is reproduced from stackoverflow.com, please click
density-plot ggplot2 r

Density plot and histogram in ggplot2

发布于 2020-07-24 12:33:33

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

enter image description here

Questioner
Adrián Valls Carbó
Viewed
8
chemdork123 2020-05-02 02:55

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)

enter image description here

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)

enter image description here