Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fitting a density curve to a histogram in R

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.

like image 906
user5243421 Avatar asked Sep 30 '09 11:09

user5243421


People also ask

How do I add a density curve to a histogram in R?

In order to add a density curve over a histogram you can use the lines function for plotting the curve and density for calculating the underlying non-parametric (kernel) density of the distribution. The bandwidth selection for adjusting non-parametric densities is an area of intense research.

How do you overlay the density curve on top of a histogram in R?

In this method to overlay the histogram with the fitted density curve, the user first needs to install and import the ggplot2 package in the R console, and call the ggplot() function which will create the plot of the given data with the required parameters and add the geom_histogram() to create the histogram of the ...


1 Answers

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 lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density 

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 lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2)  

along with the graph it produces:

enter image description here

like image 83
Dirk Eddelbuettel Avatar answered Oct 07 '22 16:10

Dirk Eddelbuettel