Search code examples
rggplot2survival-analysisfacet-wrap

Changing facet_wrap Graph Titles for Survival Curves


I have 5 survival curves I currently need to format for a research paper. The code for my survivorship function is below.

all<-survfit(Surv(MD,Censor)~DepTyp,data=add,conf.type='log-log')

From the code above, I generate 5 survival curves, and I would like to use ggplot's facet_wrap to and structure them. My code ggplot code is:

sg<-summary(all) 
ggplot()+geom_line(all,mapping=aes(x=time,y=surv))+facet_wrap(sg$strata,ncol=2)

Where sg is a summary of the each survival curve. My problem is trying to change the titles of the faceted survival curves. Currently, each curve is titled like "Title=A". I want to change each title to their formal names, ie "Female". I used the labeller functions, but had no luck, and I'm assuming its because of the way the strata is factored. I could use the ggsurvplot function, but I like the way the facet looks, I just need to change the titles. Is there anyway I can do this or do I need to use a different graphing package?


Solution

  • One way is to use labeller to modify facet label text. Another way is to modify the data to change the labels of strata variable. Since I do not have your survival data, I use diab_df data from chest as an example:

    library(survival)
    library(ggplot2)
    library(chest)  # example data diab_df
    # Fit model 
    all <- survfit(Surv(t0, t1,Endpoint) ~ Sex, 
                 data =diab_df,conf.type='log-log')
    all <- broom::tidy(all)
    
    # Original plot
    ggplot(data = all, aes(x = time, y = estimate))+
      geom_line()+ 
    facet_wrap(.~strata)
    

    
    # Solution 1: 
    stratalabs <- c("Male", "Female")
    names(stratalabs) <- c("Sex=1", "Sex=2")
    ggplot(data = all, aes(x = time, y = estimate))+
      geom_line()+ 
      facet_wrap( .~ strata, labeller = labeller(strata = stratalabs))
    

    
    # Solution 2: 
    all$strata = factor(all$strata, levels = c("Sex=1", "Sex=2"), 
                       labels = c("Male", "Female"))
    ggplot(data = all, aes(x = time, y = estimate))+
      geom_line() + 
      facet_wrap( .~ strata)
    

    Created on 2020-01-01 by the reprex package (v0.3.0)