I would like to plot discrete probability distributions (like the poisson distribution) using ggplot2.
I was able to plot it without using ggplot2 like this.
plot( dpois( x=0:20, lambda=1 ), type="b")
And, I was able to plot continuous probability distributions using ggplot2 like this.
ggplot(data.frame(x=c(-10,10)), aes(x)) + stat_function(fun=dnorm, args=list(0, 1))
And the code I tried was:
ggplot(data.frame(x=c(0:10)), aes(x)) + stat_function(geom="point", fun=dpois, args=list(1))
In ggplot2, How do I plot discrete probability distributions like first one?
The ggplot
functions would have no idea where your pdf has support. If you want to plot a discrete pdf, you'll need to calculate the points yourself. And usually it makes more sense to plot these as a bar chart since it's inappropriate to interpolate probabilities between discrete values.
ggplot(transform(data.frame(x=c(0:10)), y=dpois(x, 1)), aes(x, y)) +
geom_bar(stat="identity")
stat_function
will try to interpolate between the boundary values using default n=101
points. Issue with discreet distributions is that x has to hit the integer values. Try specifying n=11 in your example:
ggplot(data.frame(x=c(0:10)), aes(x)) +
stat_function(geom="point", n=11, fun=dpois, args=list(1))
a lot simpler and much more straightforward is to use geom_point
in this case:
ggplot(data.frame(x=c(0:10)), aes(x)) +
geom_point(aes(y=dpois(x, 1)), colour="red")
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