Reorder legend survfit

Viewed 238

I have made a regression that looks like this:

survfit(Surv(YearsToEvent, Event) ~ CancerType, data = RegressionData)

From that I get an output table like this (I removed some of the columns for readability):

          n 
Cancer A  100  
Cancer B  200  

However, when I plot the output using ggsurvplot where I have a plot + a table with "number at risk", I want to be able to manually adjust the order of the legend. That is, I want to be able to put Cancer B before Cancer A. I found a similar thread here on SO: How to reorder strata in survfit object for ggsurvplot legend?. However, I did not find any answer in it. I have tried to sort the data frame RegressionData before the regression, without sucess.

Could anyone help me out here?

1 Answers

Here is an example how you could achieve what you want:

The main step is to transfrom the grouping variable to factor class. Then you can define the levels by hand:

The other steps are the same:

library(survminer)
library(survival)
library(tidyverse)

lung1 <- lung %>% 
  mutate(sex = factor(sex, levels = c(2, 1)))
  
ggsurvplot(
  fit = survfit(Surv(time, status) ~ sex, data = lung1),
  risk.table = TRUE,
  xlab = "Days", 
  ylab = "Overall survival probability")

enter image description here

Related