tags:

views:

100

answers:

2

Hi, 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? Thank you!

A: 
load(ggplot2)
x <- seq(0,1,length=100)
db <- dbeta(x, 1, 1)

You can use the qplot function within ggplot2 to make a quick plot

qplot(x, db, geom="line")

or you can add a geom_line layer to a ggplot

ggplot() + geom_line(aes(x,db))
Brian
Did you mean `require(ggplot2)` or `library(ggplot2)` in the first line of your answer?
Gavin Simpson
+1  A: 

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
Gavin Simpson