如何在 ggplot2 中绘制 Gamma 分布

Ale*_*lex 2 r gamma-distribution ggplot2

我在 R 中有一个图,我想在 ggplot2 中复制它。我有以下代码:

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我试图在 ggplot2 中复制这个图,这是我能得到的最接近的图。

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

在此处输入图片说明

MrF*_*ick 5

您没有正确匹配您的参数。的签名dgamma

dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)
Run Code Online (Sandbox Code Playgroud)

所以当你打电话

dgamma(theta, 0.5, 1)
Run Code Online (Sandbox Code Playgroud)

那是

dgamma(theta, shape=0.5, rate=1)
Run Code Online (Sandbox Code Playgroud)

这意味着您将翻译ggplot

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

如果您喜欢scale_y_continuous(limits=c(0,12))或类似的东西,您也可以调整 y 限制。