Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting the poisson distribution using ggplot2's stat_function

Tags:

r

ggplot2

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")

enter image description here

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))

enter image description here

And the code I tried was:

ggplot(data.frame(x=c(0:10)), aes(x)) + stat_function(geom="point", fun=dpois, args=list(1))

enter image description here

In ggplot2, How do I plot discrete probability distributions like first one?

like image 704
ksmzn Avatar asked Dec 25 '14 05:12

ksmzn


2 Answers

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")

enter image description here

like image 121
MrFlick Avatar answered Nov 09 '22 20:11

MrFlick


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))

enter image description here

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")

enter image description here

like image 14
s-v-r Avatar answered Nov 09 '22 20:11

s-v-r