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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With