How can I overlay a density plot (normal curve) over a histogram?

How can I overlay a density plot (normal curve) over a histogram?

book

Article ID: KB0080747

calendar_today

Updated On:

Products Versions
Spotfire S+ All supported versions

Description

User looking for S+ code to overlay a density plot (normal curve) over a histogram.

 

Issue/Introduction

How can I overlay a density plot (normal curve) over a histogram?

Environment

Product: TIBCO Spotfire S+ Version: All supported versions OS: All supported operating systems --------------------

Resolution

Here is one approach to combining the density (normal curve) and the histogram.  The key here is the probability=TRUE argument to hist(), which puts it on a 0-1 vertical scale rather than a scale of bin counts.  Then, computing the interquartile range is a fairly reasonable way to set the horizontal scale of the density function.

x <- rnorm(500)
hist(x, prob=T)
iqd <- summary(x)[5] - summary(x)[2]
lines(density(x, width=2*iqd))

References:
You can view the help files on any of the functions used in the code above by typing a question mark followed by the function name at your S+ command prompt.  For example:

> ?hist
> ?density