Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overlap histogram and density plot with Numbers on Y-axis instead of density

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:

img1

The initial density plot for the same data:

img2

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

img3

like image 610
Eugene Avatar asked Jan 25 '26 03:01

Eugene


1 Answers

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") 

enter image description here

like image 65
Aaron left Stack Overflow Avatar answered Jan 27 '26 21:01

Aaron left Stack Overflow



Donate For Us

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