代码之家  ›  专栏  ›  技术社区  ›  Alex

在R中如何调用dbeta的函数

  •  0
  • Alex  · 技术社区  · 7 年前

    #emp bayes
    num_trials <- 10e6
    
    simulations <- data_frame(
      true_average = rbeta(num_trials, 81, 219),
      hits = rbinom(num_trials, 300, true_average)
    )
    
    hit_100 <- simulations %>%
      filter(hits == 100)
    
    dens <- function(z) dbeta(z, 81 + 100, 219 + 200)
    
    ggplot(hit_100, aes(true_average)) +
      geom_histogram(aes(y = ..density..),bins = 100) +
      stat_function(color = "red", fun = dens) +
      labs(x = "Batting average of players who got 100 H / 300 AB")
    

    enter image description here

    我了解R函数的基本知识,例如

    square.it <- function(x) {
        square <- x * x
        return(square)
    }
    # square a number
    square.it(5)
    
    ## [1] 25
    

    但密度函数的不同之处在于,没有输入值 z

    dens <- function(z) dbeta(z, 81 + 100, 219 + 200)
    

    或线路

    stat_function(color = "red", fun = dens)
    

    所以我的问题是,当密度函数没有提供值时,R如何在ggplot中创建平滑函数?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Brian    7 年前

    http://ggplot2.tidyverse.org/reference/stat_function.html

    可以将其他参数包装到函数中 args = list(...)

      ggplot(hit_100, aes(true_average)) +
        geom_histogram(aes(y = ..density..),bins = 100) +
        stat_function(color = "red", fun = dbeta, 
                      args = list(shape1 = 81+100, shape2 = 219+200)) +
        labs(x = "Batting average of players who got 100 H / 300 AB")
    

    它仍然会自动转储插值的 x x 它使用的值本质上是 seq(min(hit_100$true_average), max(hit_100$true_average), length.out = 101) stat_function 使用 n =

        2
  •  1
  •   AK88    7 年前

    stat_function 使在现有绘图上叠加函数变得容易。如果您设置 data hit_100 .

    Take a look at here