장원준
장원준

Reputation: 11

How can I add a text in R studio ggsurvplot?

I'm having a difficulty with the ggsurvplot function.

All I want to do is just adding a two-line text on the ggsurvplot.

Since those 'gg-' things would not accept '+', the last step of my study is stucked for a week.

Help me.

Thanks.

1 text

text(x = 20, y = 0.8, label = median_survival_ia_UFS, col = "blue", cex = 1.2)
text(x = 20, y = 0.7, label = median_survival_ia_NAT, col = "red", cex = 1.2)

2 grob

library(gridExtra)
combined_plot <- grid.arrange(p$plot, p_text, heights = c(0.9, 0.1))
text_grob <- grobTree(textGrob(label = text_data$label, 
                      x = text_data$x, y = text_data$y, just = "centre"))

p <- arrangeGrob(nullGrob(), p, text_grob, 
         heights = unit.c(unit(0.9, "npc"), unit(0.1, "npc")), nrow = 2)
print(p)   #Where p represents ggsurvplot

Upvotes: 1

Views: 200

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24252

Below, I propose a solution that is not elegant, but it is effective.
There is certainly a simpler solution, but even from this one, some useful lessons can be drawn.

library(survminer)
library(survival)

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

df_txt <- data.frame(x=700, y=0.8, lab="Kaplan-Meier curves\n by sex")
p$plot$layers[[4]] <- layer(geom="text", position="identity", stat="identity",
                            mapping=aes(x=x, y=y, label=lab), data=df_txt,
                            params=list(size=6, color="blue")) 
print(p)

enter image description here

Upvotes: 0

Related Questions