Alex
Alex

Reputation: 2780

How to plot a Gamma distribution in ggplot2

I have a plot in R that I am trying to replicate in ggplot2. I have the following code:

theta = seq(0,1,length=500)
post <- dgamma(theta,0.5, 1)
plot(theta, post, type = "l", xlab = expression(theta), ylab="density", lty=1, lwd=3)

enter image description here

I have tried to replicate this plot in ggplot2 and this is the closest I was able to get.

df=data_frame(post,theta)
ggplot(data=df,aes(x=theta))+
  stat_function(fun=dgamma, args=list(shape=1, scale=.5))

enter image description here

Upvotes: 2

Views: 8297

Answers (1)

MrFlick
MrFlick

Reputation: 206167

You didn't match up your parameters correctly. The signature of dgamma is

dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)

so when you call

dgamma(theta, 0.5, 1)

that's

dgamma(theta, shape=0.5, rate=1)

which means you would translate the ggplot as

ggplot(data=df,aes(x=theta))+
  stat_function(fun=dgamma, args=list(shape=0.5, rate=1))

you could also adjust the y-limits if you like with scale_y_continuous(limits=c(0,12)) or something similar.

Upvotes: 5

Related Questions