Plot line over Histogram

Hi,
I would like to draw a line on this histogram:

hist(rnorm(100, mean=15, sd=1), xlim=range(11:19), main="Size 100", xlab="x")

The line must show that this histogram is a Gaussian Curve!

I hope the question is understandable...

That's a little tricky since the area under a Gaussian integrates to one, while a histogram plots frequencies/counts.

As @EconomiCurtis points out, you have to change from a frequency histogram to a density histogram. It's all downhill from there:

data <- rnorm(100, mean=15, sd=1)
hist(data, xlim=range(11:19), main="Size 100", xlab="x", freq=FALSE)
curve(dnorm(x,mean=mean(data),sd=sd(data)), add=TRUE,col="red")

Obligatory Stack Overflow discussion: Fitting a density curve to a histogram in R - Stack Overflow

1 Like

You can also do it with ggplot2 using stat = density and stat_function():

library(dplyr)
library(ggplot2)

set.seed(100)

rnorm(100, mean=15, sd=1) %>% 
  as_tibble() %>% 
  ggplot(aes(value)) + 
  geom_histogram(stat = "density") +
  stat_function(fun = function(x) {dnorm(x, 15, 1)}, color = "red") +
  lims(x = c(11, 19))

which gives you this:

2 Likes