2

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

Alex
  • 2,603
  • 4
  • 40
  • 73

1 Answers1

5

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295