I have the histogram plot created in ggplot2 and I'd like to overlap it with density line for the same data. Importantly, I don't want to turn histogram into density values, but want to keep N (numbers) on y axis. Is there any way to overlap the histogram and density plot without transforming the histogram, but rather to scale up the density curve ?
The histogram for this data:

The initial density plot for the same data:

The desired overlay but with density on Y-axis instead of counts:

You'll want to use the ..count.. parameter created by stat_density, and then scale it by the bin width.
library(ggplot2)
set.seed(15)
df <- data.frame(x=rnorm(500, sd=10))
ggplot(df, aes(x=x)) +
geom_histogram(colour="black", fill="white", binwidth = 5 ) +
geom_density(aes(y=..count..*5), alpha=.2, fill="#FF6666")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With