Flora Grappelli
Flora Grappelli

Reputation: 679

How to use ggrepel with a survival plot (ggsurvplot)?

I would like to add the label of each survival curve at the end of the lines. I am using ggsurvplot from the Survminer package (which is based on ggplot2). I don't know how to do it with ggrepel. I didn't find any example with survival data:

require("survival")
library(survminer)
library(ggrepel)
fit<- survfit(Surv(time, status) ~ sex, data = lung)
p=ggsurvplot(fit, data = lung)$plot; 
p + geom_label_repel()

The code above throws an error.

Upvotes: 2

Views: 279

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

The object p you have created contains enough information to generate the labels. p$data is a data frame, and contains a column called strata which you can use here. You need to map the label aesthetic to this column. You will also need to filter a copy of the data to pass to the geom_label_repel layer that contains only the maximum time value for each stratum:

p + geom_label_repel(aes(label = strata),
                     data = p$data %>% 
                            group_by(strata) %>%
                            filter(time == max(time)))

enter image description here

Upvotes: 3

Related Questions