如何在ggplot 2生成的Kaplan-Meier图中为置信区间添加着色和颜色?

FTF*_*FTF 4 r ggplot2 survival-analysis ggally

我想对生存估计的置信区间进行阴影处理.现在我有黑线.

library(survival)
library(ggplot2)
library(GGally)
data(lung) 
sf.sex <- survfit(Surv(time, status) ~ sex, data = lung) 
pl.sex <- ggsurv(sf.sex, CI = TRUE) 
pl.sex
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Sam*_*son 7

这是一个简单,几乎正确的解决方案:

pl.sex <- ggsurv(sf.sex, CI = FALSE) +
  geom_ribbon(aes(ymin=low,ymax=up,fill=group),alpha=0.3)
Run Code Online (Sandbox Code Playgroud)

设置CI = FALSE为摆脱虚线CI带然后添加geom_ribbon()以获得您想要的置信带.

在此输入图像描述

然而,这只是大部分是正确的,因为我们希望置信带也使用阶梯函数.为了得到我们想要的东西,我们可以使用此链接中的一些代码stat为geom_ribbon 创建一个名为"stepribbon" 的新代码,如下所示:

library(proto)

stairstepn <- function( data, direction="hv", yvars="y" ) {
  direction <- match.arg( direction, c( "hv", "vh" ) )
  data <- as.data.frame( data )[ order( data$x ), ]
  n <- nrow( data )

  if ( direction == "vh" ) {
    xs <- rep( 1:n, each = 2 )[ -2 * n ]
    ys <- c( 1, rep( 2:n, each = 2 ) )
  } else {
    ys <- rep( 1:n, each = 2 )[ -2 * n ]
    xs <- c( 1, rep( 2:n, each = 2))
  }

  data.frame(
    x = data$x[ xs ]
    , data[ ys, yvars, drop=FALSE ]
    , data[ xs, setdiff( names( data ), c( "x", yvars ) ), drop=FALSE ]
  )
}

stat_stepribbon <- function( mapping=NULL, data=NULL, geom="ribbon", position="identity" ) {
  StatStepribbon$new( mapping=mapping, data=data, geom=geom, position=position )
}

StatStepribbon <- proto(ggplot2:::Stat, {
  objname <- "stepribbon"
  desc <- "Stepwise area plot"
  desc_outputs <- list(
    x = "stepped independent variable",
    ymin = "stepped minimum dependent variable",
    ymax = "stepped maximum dependent variable"
  )
  required_aes <- c( "x", "ymin", "ymax" )

  default_geom <- function(.) GeomRibbon
  default_aes <- function(.) aes( x=..x.., ymin = ..y.., ymax=Inf )

  calculate <- function( ., data, scales, direction = "hv", yvars = c( "ymin", "ymax" ), ...) {
    stairstepn( data = data, direction = direction, yvars = yvars )
  }

  examples <- function(.) {
    DF <- data.frame( x = 1:3, ymin = runif( 3 ), ymax=rep( Inf, 3 ) )
    ggplot( DF, aes( x=x, ymin=ymin, ymax=ymax ) ) + stat_stepribbon()
  }

})
Run Code Online (Sandbox Code Playgroud)

有了这个新的,stat你可以得到我认为你真正想要的解决方案:

pl.sex <- ggsurv(sf.sex, CI = FALSE) +
  geom_ribbon(aes(ymin=low,ymax=up,fill=group),stat="stepribbon",alpha=0.3) +
  guides(fill=guide_legend("sex"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述