R中威布尔曲线下的阴影子区域

Shading subregion under Weibull curve in R

我想像图中那样用威布尔分布做某事。

但不知何故,我无法使用 stat_function 让它工作。我收到 argument missing 错误。添加 args=list(..) 不起作用。

limitRange <- function(fun, min, max) {
  function(x) {
    y <- fun(x)
    y[x < min  |  x > max] <- NA
    return(y)
  }
}      

ggplot(data.frame(x=c(0,3)), aes(x)) +
  stat_function(fun = dweibull, 
                args = list(shape = 2, scale = 1.12), alpha = .8, size = 1.1) + # works
  stat_function(fun = limitRange(dweibull(shape = 2, scale = 1.12), 0.0297, 0.1189),
                args = list(shape = 2, scale = 1.12), #doesn't work
                geom = "area", fill = "blue", alpha = 0.2) 

非常感谢任何帮助。

你的问题是你打电话的方式 limitRange。它的第一个参数需要是一个函数,但你给它 dweibull(shape = 2, scale = 1.12),这不是一个函数。事实上,导致错误的是:

dweibull(shape = 2, scale = 1.12)
# Error in dweibull(shape = 2, scale = 1.12) : 
#  argument "x" is missing, with no default

将其转换为函数有效:

ggplot(data.frame(x = c(0, 2)), aes(x)) +
  stat_function(fun = dweibull,
                args = list(shape = 2, scale = 1.12)) +
  stat_function(
    fun = limitRange(function(z) dweibull(z, shape = 2, scale = 1.12), 0.0297, 0.1189),
    geom = "area",
    fill = "blue",
    alpha = 0.2
  ) 

一个整体更简洁的方法是给 limitRange 一个 ... 参数 fun:

limitRange <- function(fun, ..., min, max) {
  return(function(x) {
    y <- fun(x, ...)
    y[x < min  |  x > max] <- NA
    return(y)
  })
}

ggplot(data.frame(x = c(0, 2)), aes(x)) +
  stat_function(fun = dweibull,
                args = list(shape = 2, scale = 1.12)) +
  stat_function(
    fun = limitRange(dweibull, shape = 2, scale = 1.12, min = 0.0297,  max = 0.1189)
    geom = "area",
    fill = "blue",
    alpha = 0.2
  ) 

您需要以这种方式命名 minmax 参数(如果 fun 使用 minmax 参数可能会导致错误...更多独特的名字可能会更好)。