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 # 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")
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:
I found these couple of lines of code succinct but extremely helpful for plotiing a non-standard density over a histogram - Thanks
Thanks for this useful post!
very helpful. thank you
Post a Comment
<< Home