[英]How to plot this function with ggplot?
我有這個算法,它允許我通過給我 x 的值來從 Beta 分布中采樣
xx <- c ()
num <- 0
for (j in 1:100) {
U <- 2;X <- 0;
while (U > dbeta (X ,4 ,2) / 8) {
X <- runif (1)
U <- runif (1)
num <- num + 1
}
xx [j] <- X
}
然后我用標准 plot 成功地繪制了它
x=seq(0,1,0.01)
hist (xx , prob = TRUE , xlim =c (0,1) )
lines (x , dbeta (x ,4 ,2) , lwd =2 , col = 'red')
但是我怎么能用ggplot plot呢? 天平似乎在這里不起作用。
ggplot(data.frame(xx), aes(xx)) + geom_histogram() + stat_function(fun = dbeta, args = c(4, 2))
要使線與直方圖匹配,它必須是密度的直方圖,而不是計數的直方圖,默認是計數(箱)。
我還更改了 colors 和背景。
ggplot(data.frame(xx), aes(xx)) +
geom_histogram(aes(y = ..density..),
color = 'darkgrey', fill = 'lightgrey', bins = 8) +
stat_function(fun = dbeta, args = c(4, 2), color = 'red') +
theme_bw()
數據生成代碼
通過設置 RNG 種子,數據以可重現的方式生成。
set.seed(2020)
n <- 100
xx <- numeric(n)
num <- 0
for (j in 1:n) {
U <- 2;X <- 0;
while (U > dbeta (X ,4 ,2) / 8) {
X <- runif (1)
U <- runif (1)
num <- num + 1
}
xx[j] <- X
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.