Monday, August 22, 2005

Superimposing a density line on a histogram

How to plot a histogram with a line indicating a density? Two suggested ways: one is with lines, and another one is with plot.function (Ingmar had trouble with the former).

# first: a histogram -- use freq=FALSE to normalize the area
# occupied by the histogram
hist(rnorm(1e4), 50, freq=FALSE)

# with lines
x = seq(-4, 4, len=200)
y = dnorm(x)
lines(x, y, col="blue")

# or with plot.function
plot( function(x) dnorm(x,m=0,s=1), -4, 4, n=200, add=TRUE, col="red")

# or with curve
curve( dnorm(x,m=0,s=1), -4, 4, n=200, add=TRUE, col="red")
In plot.function, the first argument is the (vectorized) function to be plotted. Here an inline function is defined (a function without name), because you may need to specify arguments which cannot otherwise be specified (yet—I hope this will change in future versions of R). The parameter n specifies the number of points to be used to plot the line. The result is:

3 Comments:

Anonymous Anonymous said...

I found these couple of lines of code succinct but extremely helpful for plotiing a non-standard density over a histogram - Thanks

27 August, 2009 03:12  
Blogger Unknown said...

Thanks for this useful post!

07 October, 2009 23:12  
Anonymous te said...

very helpful. thank you

05 February, 2010 17:17  

Post a Comment

<< Home