Search code examples
rggplot2graphsurvival-analysissurvival

Change legend labels in ggsurvfit ggplot


I am doing a Kaplan-Meier using ggsurvfit. This is my code

p <- survfit2(Surv(time, death)~female, data=df) 

p %>%
ggsurvfit(type = "survival", linewidth=1) +
  labs(
      title = "Kaplan-Meier Curve",
      y = "Survival probability",
      x = "Time, days") + 
    coord_cartesian(xlim=c(0,30)) +
  add_legend_title("Sex") +
  scale_x_continuous(breaks = c(0, 5,10,15,20,25,30)) +
  scale_y_continuous(expand = c(0.01,0)) +
  scale_color_manual(values = c('dodgerblue2', 'orchid2')) +
  scale_fill_manual(values = c('dodgerblue2', 'orchid2')) +
  theme_gray() +
  theme(legend.position = "bottom") +
  add_censor_mark() +
  add_confidence_interval() +
  add_risktable(risktable_group = "risktable_stats") + 
  add_pvalue(caption="Log-rank {p.value}",
             location = "annotation", x =4, y=0.10) +
  add_quantile(x_value = 30, linetype = "dotted", color = "grey30", linewidth = 0.8) + 
  add_risktable_strata_symbol(symbol = "\U25CF", size = 10)

The problem is that I don't know how to change the legend labels in the legend, as they appear like this:

enter image description here

On the website of ggsurvfit it is written that "Publishable Legends: Raw variable names do not appear in the figure legend, e.g. "sex=Female"" and also on the examples there is Male and Female (see below), however I cannot manage to do the same and I don't know what to write.

enter image description here

Can please someone help me?


Solution

  • You need to use the labels argument in scale_fill_manual and scale_color_manual to pass your label names. This is not specific to ggsurvfit, but is true for all ggplot-based plots

    p <- survfit2(Surv(time, status)~sex, data=lung) 
    
    p %>%
      ggsurvfit(type = "survival", linewidth=1) +
      labs(
        title = "Kaplan-Meier Curve",
        y = "Survival probability",
        x = "Time, days") + 
      coord_cartesian(xlim=c(0,30)) +
      add_legend_title("Sex") +
      scale_x_continuous(breaks = c(0, 5,10,15,20,25,30)) +
      scale_y_continuous(expand = c(0.01,0)) +
      scale_color_manual(values = c('dodgerblue2', 'orchid2'),
                         labels = c('My label', 'My other label')) +
      scale_fill_manual(values = c('dodgerblue2', 'orchid2'),
                        labels = c('My label', 'My other label')) +
      theme_gray() +
      theme(legend.position = "bottom") +
      add_censor_mark() +
      add_confidence_interval() +
      add_risktable(risktable_group = "risktable_stats") + 
      add_pvalue(caption="Log-rank {p.value}",
                 location = "annotation", x =4, y=0.10) +
      add_quantile(x_value = 30, linetype = "dotted", 
                   color = "grey30", linewidth = 0.8) + 
      add_risktable_strata_symbol(symbol = "\U25CF", size = 10)
    

    enter image description here