Search code examples
rggplot2graphsurvival-analysissurvival

Survival analysis in ggplot in R


I coded the following (I used data=lung)

library(ggsurvfit)
library(ggplot2)

p <- survfit2(Surv(time, status)~sex, data=lung) 
ggsurvfit(p,
          type = "survival"
          ) 
          add_censor_mark() %>%
          add_confidence_interval() %>%
          add_risktable() 

I have two problems:

  1. R says there is an error: Error in match.arg(type) : 'arg' must be NULL or a character vector However I copied the code exactly as in the examples https://www.danieldsjoberg.com/ggsurvfit/reference/ggsurvfit.html

  2. In the plot the confidence intervals and risk table are not shown. When I use the same dataset and variables but with another code and another package, the confidence intervals are displayed but the image appears to be distorted and the risk table is not shown and it is overlapping...

    sfit <- survfit(Surv(day, death)~male, data=db)
     sfit
     summary(sfit)
    
     library(survminer)
     ggsurvplot(sfit)
    
     ggsurvplot(sfit, conf.int=TRUE, pval=TRUE, risk.table=TRUE, 
                legend.labs=c("Male", "Female"), legend.title="Sex",  
                palette=c("dodgerblue2", "orchid2"), 
                title="Kaplan-Meier Curve for Lung Cancer Survival", 
                risk.table.height=.15)
    

enter image description here

I would like to use the first code since as far as I know it can be more customizable, however other options are well accepted as well..


Solution

  • You haven't copied the examples correctly. You need to use a + to add the components to the plot. You are using %>%, which doesn't make sense in this context.

    library(survival)
    library(ggplot2)
    library(ggsurvfit)
    
    p <- survfit2(Surv(time, status)~sex, data=lung) 
    
    ggsurvfit(p, type = "survival") +
      add_censor_mark() +
      add_confidence_interval() +
      add_risktable() 
    

    Created on 2023-03-04 with reprex v2.0.2