【问题标题】:Basic Calculations with stat_functions -- Plotting hazard functions使用 stat_functions 进行基本计算——绘制危险函数
【发布时间】:2017-11-26 21:10:26
【问题描述】:

我目前正在尝试使用 R 的 ggplot2 绘制一些密度分布函数。我有以下代码:

f <- stat_function(fun="dweibull",
                   args=list("shape"=1),
                             "x" = c(0,10))
stat_F <- stat_function(fun="pweibull",
                   args=list("shape"=1),
                             "x" = c(0,10))
S <- function() 1 - stat_F

h <- function() f / S
wei_h <- ggplot(data.frame(x=c(0,10))) +
         stat_function(fun=h) +
         ...

基本上我想根据具有不同参数的 Weibull 分布绘制危险函数,这意味着我想绘制:

上面的代码给了我这个错误:

stat_function() 中的计算失败: 未使用的参数 (x_trans)

我也试过直接用

S <- 1 - stat_function(fun="pweibull", ...)

而不是上面的“解决方法”与自定义函数构造。这引发了另一个错误,因为我试图对一个对象进行数值算术:

二元运算符的非数字参数

我收到了这个错误,但我不知道解决方案。

我做了一些研究,但没有成功。我觉得这应该是直截了当的。我也想尽可能地“手动”完成,但如果没有简单的方法来做到这一点,那么打包的解决方案也可以。

提前感谢您的任何建议!

PS:我基本上想重新创建您可以在链接的 PDF 文件第 10 页上的Kiefer, 1988 中找到的图表。

【问题讨论】:

    标签: r ggplot2 statistics hazard


    【解决方案1】:

    三个cmets:

    1. stat_function 是 ggplot2 的函数统计,您不能将两个 stat_function 表达式相除或以其他方式在数学表达式中使用它们,如 S &lt;- 1 - stat_function(fun="pweibull", ...)。这是对stat_function 的基本误解。 stat_function 始终需要添加到 ggplot2 图中,如下例所示。

    2. stat_functionfun 参数将函数作为参数,而不是字符串。如果您需要尚不存在的函数,您可以动态定义函数。

    3. 您需要通过aes 函数设置美学映射。

    此代码有效:

    args = list("shape" = 1.2)
    ggplot(data.frame(x = seq(0, 10, length.out = 100)), aes(x)) + 
      stat_function(fun = dweibull, args = args, color = "red") +
      stat_function(fun = function(...){1-pweibull(...)}, args = args, color = "green") +
      stat_function(fun = function(...){dweibull(...)/(1-pweibull(...))},
                    args = args, color = "blue")
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2021-12-25
      相关资源
      最近更新 更多