# Fitting a density curve to a histogram in R

### Question

Is there a function in R that fits a curve to a histogram?

Let's say you had the following histogram

``````hist(c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
``````

It looks normal, but it's skewed. I want to fit a normal curve that is skewed to wrap around this histogram.

This question is rather basic, but I can't seem to find the answer for R on the internet.

1
83
11/16/2012 4:38:00 PM

If I understand your question correctly, then you probably want a density estimate along with the histogram:

``````X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
``````

Edit a long while later:

Here is a slightly more dressed-up version:

``````X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
``````

along with the graph it produces: 148
5/4/2014 6:33:03 PM

Such thing is easy with ggplot2

``````library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5),
rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..)) +
geom_density()
``````

or to mimic the result from Dirk's solution

``````ggplot(dataset, aes(x = X)) +
geom_histogram(aes(y = ..density..), binwidth = 5) +
geom_density()
``````