首页 > 解决方案 > R中威布尔曲线下的着色子区域

问题描述

我想在图中用 Weibull 分布做某事。在此处输入图像描述

但不知何故,我无法使用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) 

非常感谢任何帮助。

标签: rggplot2weibull

解决方案


你的问题是你打电话的方式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参数可能会导致错误......更多唯一的名称可能会更好)。


推荐阅读