【问题标题】:How is a function of dbeta being called in R如何在 R 中调用 dbeta 的函数
【发布时间】:2017-07-21 02:08:54
【问题描述】:

我有以下代码

#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")

我了解 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 中创建平滑函数?

【问题讨论】:

  • 我猜是因为dens()只有一个参数传入了正确的对象。

标签: r function ggplot2


【解决方案1】:

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)。 101 可在stat_function 内使用n = 进行调整。

【讨论】:

    【解决方案2】:

    stat_function 可以轻松地将函数叠加到现有绘图之上。如果将 data 设置为 NULL,则数据将从调用 ggplot 中指定的绘图数据继承。所以,基本上,在你的情况下,正在输入的数据是hit_100

    Take a look at here

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 2020-02-21
      • 2018-02-07
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2021-12-05
      • 2014-02-14
      • 1970-01-01
      相关资源
      最近更新 更多