简体   繁体   中英

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

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

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? 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.

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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