Suppose you want to plot a density histogram and a pdf simultaneously. As an example, here I’ll simulate a large number of random draws from a standard normal distribution and overlay the standard normal pdf \[ f(x) = \frac 1{\sqrt{2\pi}}e^{x^2/2}. \]
Here are a two ways the plot can be produced. I’ll use the truehist
function from the MASS library to draw the histogram; it produces density histograms by default.
myhist <- MASS::truehist
Now generate the random sample.
set.seed(1)
n <- 100000
xs <- rnorm(n)
lines
For the first method, we create a new plot with the truehist
function, and then we can use the function lines
to add points connected by lines to the plot.
myhist(xs)
xvec <- seq(-4, 4, by=.01)
yvec <- 1/sqrt(2*pi) * exp(-xvec^2 / 2)
lines(xvec, yvec, col="red", lwd=2) # lwd=2 for a thicker curve
curve
If the functions we are plotting act nicely on vectors, we can use the function curve
, which plots an expression written as a function of x. For this plot, for variety let’s also add big magenta vertical dashed lines at \(-2\) and \(2\).
myhist(xs)
xvec <- seq(-4, 4, by=.01)
curve(1/sqrt(2*pi) * exp(-x^2 / 2), -4, 4, col="red", lwd=2, add=TRUE)
abline(v = c(-2,2), col="magenta", lty="dashed", lwd=3)
Here in the curve
command, the argument add=TRUE
tells R to add the curve to an existing plot rather than start a new plot.