Remove variable name from legend in ggsurvplot
Asked Answered
H

3

6

Is there a concise way to remove the variable name in the legend of plots created by ggsurvplot? Example:

library(survival)
library(survminer)

set.seed(123)
df=data.frame(gender=c(rep("male", 10), rep("female", 10)), value=c(rnorm(10,mean = 2), rnorm(10,mean = 3)))
fit = surv_fit(Surv(value) ~ gender, data = df)
p = ggsurvplot(fit, data = df,  surv.median.line = "none") 

enter image description here

What I want is to remove the word 'gender' from the legend as in the following plot. I can achieve this by manually setting the legend labels:

p = ggsurvplot(fit, data = df,  surv.median.line = "none", legend.labs = c("male", "female")) 

But is there a better way?

EDIT: I accidentally swapped male and female when I manually assigned the gender (2. plot), which shows how dangerous this method is.

enter image description here

Holcombe answered 12/5, 2020 at 8:56 Comment(0)
U
8

Hack the strata with gsub.

names(fit$strata) <- gsub("gender=", "", names(fit$strata))
ggsurvplot(fit, data=df, surv.median.line="none")

enter image description here

Uphroe answered 12/5, 2020 at 9:6 Comment(1)
Works fine, thanks a lot! Even though I was hoping for an option included by the makers of the package.Holcombe
I
5

To avoid the mistake of swapping the legend labels, use this option in the ggsurvplot function instead: legend.labs = levels(df$gender)

Interventionist answered 17/6, 2020 at 15:52 Comment(1)
This is an ideal solution!Ozonize
B
0

you can simply change the attribute of strata

attr(fit$strata,'names') <- c('female', 'male')

and then make the plot

p = ggsurvplot(fit, surv.median.line = "none") 
Bonanza answered 12/5, 2020 at 9:15 Comment(1)
Yes, thanks for your answer. But I don't want to type 'male', 'female' manually.Holcombe

© 2022 - 2024 — McMap. All rights reserved.