rggplot2survminer

Adding a new custom table to ggsurvplot


I'd like to add a table to the upper right corner of the KM plot by survminer::ggsurvplot(). I got to as far as creating the KM plot and the stats for median, HR, and p-value, but not sure how to add create a nice table to add to the plot if that's possible. Here's my code so far.

library(survival)
library(lubridate)
library(ggsurvfit)
library(gtsummary)
library(tidycmprsk)
library(condsurv)

# stats for number of events and median survival time with 95% CI
km <- survfit(Surv(time, status) ~ sex, data = lung)

# stats for hr and p-value
hr <- coxph(Surv(time, status) ~ sex, data = lung) 
  
# plot to add custom table to upper right corner, while keeping the risk table
p <- ggsurvplot(km, risk.table = T, risk.table.col = c('sex'), 
                risk.table.height = 0.25, ggthem = theme_light(),
                xlab = 'Time',  break.time.by = 20, 
                risk.table.y.text = F, risk.table.y.text.col = T, risk.table.title="Number at risk", 
                ggtheme = theme_classic()) 

p

The table to be added to the upper right corner with layout similar to the one in the top of this plot. enter image description here


Solution

  • Here is a solution using ggpp::annotate(), I used the built-in "lung" database in the survival package:

    ### Loading the libraries
    library(ggsurvfit)
    library(survival)
    library(survminer)
    library(ggplot2)
    library(ggpp)
    
    ### Generating the table
    df <- data.frame(col1 = 1:3, col2 = c("one", "two", "three"))
    
    ### Plotting the KM survival
    fit <- survfit(Surv(time, status) ~ sex, data = lung)
    p <- ggsurvplot(fit, data = lung) 
    
    ### Adding your table to the ggsurvplot item
    p$plot + ggpp::annotate(geom = "table", x = 700, y = 0.9, label = list(df))
    

    Note that for the exact location of the table you have to play with the x and y arguments inside the annotate().