Ggsurvplot (Survminer) Draw Rectangle on Plot

Ggsurvplot (Survminer) Draw Rectangle on Plot

I'm using ggsurvplot to draw survival curve comparisons. I'd like to customise my plot by drawing a shaded rectangle on a certain interval between two values of the x-axis. How can I do this?

Assume I am running the following code:

require("survival")
fit<- survfit(Surv(time, status) ~ sex, data = lung)

# Basic survival curves
ggsurvplot(fit, data = lung)

Let's say I want to add a shaded rectangle between Time 0 and Time 250.

Thanks a lot in advance

Luca

1 Answer

A ggsurvplot object is basically a list which contains a ggplot object as an element plot. Hence, you could always manipulate this plot element using default methods, e.g. you could use annotate to add e rectangle. However, the tricky part with adding a new layer is that it will be plotted on top of the existing layers. Hence one has to take account of that and add it at the right position in the list of layers. In the code below I simply added the rectangle as the first element of the list of layers:

library(survival)
library(survminer)

fit <- survfit(Surv(time, status) ~ sex, data = lung)
p <- ggsurvplot(fit, data = lung)

p$plot$layers <- c(annotate(geom = "rect", xmin = 0, xmax = 250, ymin = -Inf, ymax = Inf, fill = "purple"), p$plot$layers)

p
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.