How to use ggplot to plot probability densities?
ggplot2 has a stat_function() function to superimpose a function on a plot in much the same way as curve() does. I struggled a little bit to get this to work without generating the data until I realised how to use the variables produced by the statistics --- here...y... The following is similar to what we would get with curve(dbeta(x, shape1 = 2, shape2 = 2), col = "red"):
require(ggplot2)
x <- seq(0, 1, len = 100)
p <- qplot(x, geom = "blank")
stat <- stat_function(aes(x = x, y = ..y..), fun = dbeta, colour="red", n = 100,
args = list(shape1 = 2, shape2 = 2))
p + stat
We can also use the qplot function within ggplot2 to make a quick plot
qplot(x, db, geom="line")