How to use ggplot to build probability density?

I am looking for a ggplot way to build a probability density function (or any function). To do this, I used the old plot() function in R. For example, to build 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 to do it in ggplot?

+4
source share
2 answers
 library(ggplot2) x <- seq(0,1,length=100) db <- dbeta(x, 1, 1) 

You can use the qplot function in ggplot2 to make a quick graph

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

or you can add geom_line layer to ggplot

 ggplot() + geom_line(aes(x,db)) 
+6
source

ggplot2 has a stat_function() function to overlay the function on the graph in the same way as curve() . I tried a little to get this to work without generating data, until I figured out how to use the variables created by the statistics --- 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 
+6
source

All Articles