在调整后的生存曲线中自定义线型 ggadjustedcurves (survminer, ggplot2)

Customising line type in adjusted survival curves ggadjustedcurves (survminer, ggplot2)

我正在尝试绘制调整后的生存曲线,但很难按组更改线条类型。我可以使用典型的 ggplot2 语言自定义绘图的其他方面,但我遇到了更改线型的障碍。

示例:

library(survival)
library(survminer)

fit2 <- coxph( Surv(stop, event) ~ size + strata(rx), data = bladder )

ggadjustedcurves(fit2,
                 variable = "rx", 
                 data = bladder,
                 method = "average",
                 palette = c("#E69F00", "#56B4E9"),
                 size = 1.3,
                 legend = "right",
                 legend.title = expression(bold("Legend title")),
                 xlab = "Time",
                 font.legend = 12) +
  theme(legend.text.align = 0.5)

我试过添加:

geom_line( aes( linetype = c(1, 2) )
add.params = list(linetype = c(1, 2))

而且只是

linetype = c(1, 2)

但似乎没有任何效果。

首先你需要看一下代码。

ggadjustedcurves

似乎 ggadjustedcurves 将其所有参数传递给依赖于 "method" 参数的辅助函数,在本例中为 "average",所以现在看看那个(隐藏的)函数:

 getAnywhere( ggadjustedcurves.average )

请注意,除了 "master function" 中定义的少数几个参数之外,没有接受其他参数的规定,即不使用 R 的省略号机制或除大小之外的其他可能 aes-arguments 的规范。 (它也没有使用 geom_line。)所以你需要改变 both 主函数 辅助函数来接受一个 "linetype" 参数。在这里,我展示了如何修改辅助函数(尽管这也需要对 ggadjustedcurves 函数进行修改,如果您希望它完全通用,则可能还需要对其余的辅助函数进行修改):

assignInNamespace('ggadjustedcurves.average',  

  function (data, fit, variable, size = 1, ..., linetype=linetype) 
    {
    time <- surv <- NULL
    lev <- sort(unique(data[, variable]))
    pred <- survexp(as.formula(paste("~", variable)), data = data, 
                    ratetable = fit)
    curve <- data.frame(time = rep(c(0, pred$time), length(lev)), 
                        variable = factor(rep(lev, each = 1 + length(pred$time))), 
                        surv = c(rbind(1, pred$surv)))
    ggplot(curve, aes(x = time, y = surv, color = variable)) + 
        geom_step(size = size, ..., linetype=linetype)  # not geom_line
    }, 
   pos="package:survminer")

如果您在 "geom_segment linetype" 上进行 SO 搜索,您会发现 geom_segmentgeon_step 使用的)的构造方式不便于缩短向量来修改阶跃函数结果的 "contiguous" 长度。参见 ggplot error using linetype and group aesthetics。这意味着如果您需要不同的线型,您将需要使用 for-looplapply 来构建单独的 "step-curves"。