R code for superimposing a theoretical pdf onto a histogram

A couple of examples.

Example 1

This replicates Weekly #4, problem 2. X was uniform on (0,1) and Y=sqrt(X). First we generate 10,000 variates of X and of Y and make a histogram:

x <- runif(10000)
y <- sqrt(x)

For this exercise, it is important to use a density scale on the y-axis of the histogram. The density scale is in proportion per x-unit. So, if the x units are years the density scale will be proportion-per-year. The density scale is a scaling that makes the total area under the histogram 1, which makes a histogram comparable to a theoretical pdf, which necessarily has total area of 1. Now we put on top the pdf that should fit the distribution of Y:

xx <- seq(0,1,length=101) 
yy <- 2*xx
points(xx,yy,type='l')  # that is a small case "L"

Example 2

In this example, if one proceeds as above, the skewness of the distribution distorts the visual effect of fitting the pdf to the histogram. (It is instructive to try this and see for yourself.) So we truncate off the extreme right tail.

x <- runif(10000,0,2)
y <- 1/x
z <- sort(y)  # put sorted values of y into z
hist(z[1:9000], prob=T)  # Nothing magical about 9000

Now look at the histogram for z and observe some nice value just above the maximum of z; in my case 6 worked, so ...

xx <- seq(.5,6, length=101)
yy <- 1/(2*xx^2)
points(xx,yy,type='l')