Utilise Surv object in ggplot or lattice

前端 未结 2 537
南方客
南方客 2021-02-10 01:12

Anyone knows how to take advantage of ggplot or lattice in doing survival analysis? It would be nice to do a trellis or facet-like survival graphs.


So in the end I

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 01:41

    I have been using the following code in lattice. The first function draws KM-curves for one group and would typically be used as the panel.group function, while the second adds the log-rank test p-value for the entire panel:

     km.panel <- function(x,y,type,mark.time=T,...){
         na.part <- is.na(x)|is.na(y)
         x <- x[!na.part]
         y <- y[!na.part]
         if (length(x)==0) return()
         fit <- survfit(Surv(x,y)~1)
         if (mark.time){
           cens <- which(fit$time %in% x[y==0])
           panel.xyplot(fit$time[cens], fit$surv[cens], type="p",...)
          }
         panel.xyplot(c(0,fit$time), c(1,fit$surv),type="s",...)
    }
    
    logrank.panel <- function(x,y,subscripts,groups,...){
        lr <-  survdiff(Surv(x,y)~groups[subscripts])
        otmp <- lr$obs
        etmp <- lr$exp
        df <- (sum(1 * (etmp > 0))) - 1
        p <- 1 - pchisq(lr$chisq, df)
        p.text <- paste("p=", signif(p, 2))
        grid.text(p.text, 0.95, 0.05, just=c("right","bottom"))
        panel.superpose(x=x,y=y,subscripts=subscripts,groups=groups,...)
    }
    

    The censoring indicator has to be 0-1 for this code to work. The usage would be along the following lines:

    library(survival)
    library(lattice)
    library(grid)
    data(colon)  #built-in example data set
    xyplot(status~time, data=colon, groups=rx, panel.groups=km.panel, panel=logrank.panel)
    

    If you just use 'panel=panel.superpose' then you won't get the p-value.

提交回复
热议问题