简体   繁体   English

如何用 ggplot 来 plot 这个 function?

[英]How to plot this function with ggplot?

I have this algorithm which allows me to sample from Beta distribution by giving me values of x我有这个算法,它允许我通过给我 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
}

I then plotted it successfully with the standard plot然后我用标准 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')

But how can i plot it with ggplot?但是我怎么能用ggplot plot呢? The scales don't seem to work here.天平似乎在这里不起作用。

ggplot(data.frame(xx), aes(xx)) + geom_histogram() + stat_function(fun = dbeta, args = c(4, 2)) 

To have the line match the histogram it must be a histogram of densities, not of counts, the default is to have counts (bins).要使线与直方图匹配,它必须是密度的直方图,而不是计数的直方图,默认是计数(箱)。
I have also changed the colors and the background.我还更改了 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()

在此处输入图像描述

Data generation code数据生成代码

The data is generated in a reproducible way by setting the RNG seed.通过设置 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM