Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ggplot to plot probability densities?

Tags:

r

ggplot2

I am looking for the ggplot way to plot a probability density function (or any function). I used to use the old plot() function in R to do this. For example, to plot a beta distribution with alpha=1 and beta=1 (uniform):

x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)
plot(x, db, type='l')

How can I do it in ggplot?

like image 626
Dazhi Avatar asked Oct 08 '10 18:10

Dazhi


1 Answers

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 statistic --- here ..y... The following is similar to what you 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
like image 194
Gavin Simpson Avatar answered Sep 22 '22 16:09

Gavin Simpson