Geom_density to match geom_histogram binwitdh

I would like to add a line to the distribution band graph in ggplot2 to show the average distribution, but I have problems.

The ggplot call looks like this:

ggplot(x, aes(date_received)) + geom_histogram(aes(y = ..count..), binwidth=30) + geom_density() 

gives me histogram tables for every 30 days of observations, but the density line tracks the score for each individual day, as shown below (the static bottom is from geom_density .

enter image description here

Is it possible to add a geom_density layer to overlay a line that displays the average value for counting 30-day observation groups, such as binwidth in the geom_histogram .

Any help is appreciated.

+6
source share
1 answer

According to Brian S. Diggs' answer given in this e-mail , you should multiply ..count.. in geom_density( ) by binwidth= in geom_histogram() .

 set.seed(123) df<-data.frame(x=rnorm(1000,100,15)) ggplot(df,aes(x))+ geom_histogram(binwidth = 2.5)+ geom_density(aes(y=2.5 * ..count..)) 

enter image description here

+10
source

All Articles