survminer

repository·master·Indexed 20 days ago

https://github.com/kassambara/survminer

An R package for survival analysis and high-quality visualization of survival data using ggplot2-based functions. It provides tools for drawing survival curves via ggsurvplot(), diagnostics for Cox models (ggcoxzph, ggcoxdiagnostics), forest plots (ggforest), and modern effect measures such as Restricted Mean Survival Time (ggrmst), landmark analysis (gglandmark), and milestone survival (ggmilestone). It also includes support for competing risks, CDISC ADaM time-to-event datasets, and parametric survival fit overlays.

Tokens
4.4K
Snippets
10
Records
13
Agent score
68%

What's inside survminer

  1. Overview of survminer functions

    master

    The survminer package is organized into several functional categories for survival analysis:

    Survival Curves

    • ggsurvplot(): Draws survival curves with 'number at risk', cumulative events, and cumulative censored tables.
    • arrange_ggsurvplots(): Arranges multiple ggsurvplots on a single page.
    • ggsurvevents(): Plots event time distributions.
    • ggsurvparametric(): Overlays parametric survival fits (from survreg or flexsurv) on Kaplan-Meier curves.
    • surv_summary(): Creates a data frame summary from survfit results.
    • surv_cutpoint(): Determines optimal cutpoints for continuous variables based on survival significance.
    • surv_median_followup(): Computes median follow-up time using the reverse Kaplan-Meier method.
    • pairwise_survdiff(): Performs multiple pairwise comparisons of survival curves with corrections for multiple testing.
    • weighted_logrank(): Performs weighted (Fleming-Harrington) log-rank tests.

    Modern Effect Measures

    • ggrmst() / ggrmst_difference(): Restricted Mean Survival Time (RMST) visualization with area shading and difference annotation.
    • gglandmark(): Landmark analysis to avoid immortal-time bias.
    • ggmilestone(): Milestone survival at specific timepoints.

    Diagnostics of Cox Model

    • ggcoxzph(): Graphical test of proportional hazards (wrapper for plot.cox.zph()).
    • ggcoxdiagnostics(): Displays goodness-of-fit graphs for Cox Proportional Hazards models.
    • ggcoxfunctional(): Plots continuous explanatory variables against martingale residuals to help choose functional forms.
    • ggcoxnph(): Non-proportional-hazards diagnostic panel.

    Summary of Cox Model

    • ggforest(): Draws forest plots for CoxPH models.
    • ggforest_models(): Compares covariate hazard ratios across multiple Cox models.
    • ggforest_subgroup(): Subgroup forest plots showing treatment hazard ratios and interaction p-values.
    • ggadjustedcurves(): Plots adjusted survival curves for coxph models.

    Competing Risks

    • ggcompetingrisks(): Plots cumulative incidence curves.

    Clinical Trial Data

    • surv_adtte(): Prepares CDISC ADaM time-to-event (ADTTE) datasets.
  2. Upgrade to survminer v1.0.0

    master

    The transition from version 0.5.2 to 1.0.0 is a major update that consolidates new functionality. While it introduces significant new features, it is designed to be backward compatible by keeping existing function defaults unchanged.

    Key new features include:

    • Publication Presets: Use ggsurvplot(preset = "publication" | ...) along with theme_surv_classic(), theme_surv_minimal(), or theme_surv_bold() for quick, high-quality plots.
    • Modern Effect Measures: New functions for restricted mean survival time (ggrmst(), ggrmst_difference()), milestone survival (ggmilestone()), and landmark analysis (gglandmark()).
    • Cox-model Tools: Subgroup and multi-model forest plots (ggforest_subgroup(), ggforest_models()), non-proportional-hazards diagnostic panels (ggcoxnph()), and enhanced ggadjustedcurves() with hazard-ratio annotations and number-at-risk tables.
    • Enhanced Plotting: Composable single-ggplot returns via ggsurvplot(output = "ggplot"), parametric-over-KM overlays (ggsurvparametric()), and plotmath support in legend.labs.
    • Specialized Helpers: CDISC ADTTE helper (surv_adtte()), batch weighted-log-rank wrapper (weighted_logrank()), and reverse-KM median follow-up (surv_median_followup()).
  3. Fit survival curves using survival package

    master

    Before using survminer, you must first fit a survival model using the survival package. The survfit function is typically used with a Surv object containing time and status data.

    require("survival")
    fit <- survfit(Surv(time, status) ~ sex, data = lung)
  4. Install and load survminer

    master

    You can install survminer from CRAN or the latest development version from GitHub. After installation, load the package using library("survminer") to access its survival analysis and visualization functions.

    # Install from CRAN
    install.packages("survminer")
    
    # Or install the latest version from GitHub
    if(!require(devtools)) install.packages("devtools")
    devtools::install_github("kassambara/survminer", build_vignettes = FALSE)
    
    # Load the package
    library("survminer")
  5. Advanced label customization for ggsurvplot

    master

    Because ggsurvplot() returns a list of plots (e.g., $plot, $table, $ncensor.plot), you can customize them individually using standard ggplot2 functions like labs().

    For complex font styling (size, face, color), the package provides a customize_labels() helper function that applies styles to the various components of the ggsurvplot object.

    # 1. Manual label customization using ggplot2
    ggsurv$plot <- ggsurv$plot + labs(
      title    = "Survival curves",                     
      subtitle = "Based on Kaplan-Meier estimates",  
      caption  = "created with survminer"             
    )
    
    # 2. Using customize_labels for font styling
    # font format: c(size, face, color)
    ggsurv <- customize_labels(
      ggsurv,
      font.title    = c(16, "bold", "darkblue"),         
      font.subtitle = c(15, "bold.italic", "purple"), 
      font.x        = c(14, "bold.italic", "red")
    )
  6. Customize plot labels and fonts using customize_labels()

    master

    The customize_labels() helper function allows you to apply specific font styles (size, face, color) to various components of the ggsurvplot object, including the main plot, the risk table, and the ncensor plot. The ggsurvplot object is a list containing individual ggplot objects (e.g., $plot, $table, $ncensor.plot) which can be modified using standard ggplot2::labs() calls.

    # 1. Modify labels using standard ggplot2 labs() on the list components
    ggsurv$plot <- ggsurv$plot + labs(
      title    = "Survival curves",                     
      subtitle = "Based on Kaplan-Meier estimates",  
      caption  = "created with survminer"             
    )
    
    # 2. Apply global font styles using customize_labels()
    # Format for font arguments: c(size, face, color)
    ggsurv <- customize_labels(
      ggsurv,
      font.title    = c(16, "bold", "darkblue"),         
      font.subtitle = c(15, "bold.italic", "purple"), 
      font.caption  = c(14, "plain", "orange"),        
      font.x        = c(14, "bold.italic", "red"),          
      font.y        = c(14, "bold.italic", "darkred"),      
      font.xtickslab = c(12, "plain", "darkgreen")
    )
  7. Customize survival curves with ggsurvplot()

    master

    The ggsurvplot() function supports numerous arguments to customize the visual output, including line size, color palettes, confidence intervals, p-values, and risk tables.

    ggsurvplot(
      fit, 
      data = lung, 
      size = 1,                 # change line size
      palette = 
        c("#E7B800", "#2E9FDF"),# custom color palettes
      conf.int = TRUE,          # Add confidence interval
      pval = TRUE,              # Add p-value
      risk.table = TRUE,        # Add risk table
      risk.table.col = "strata",# Risk table color by groups
      legend.labs = 
        c("Male", "Female"),    # Change legend labels
      risk.table.height = 0.25, # Useful to change when you have multiple groups
      ggtheme = theme_bw()      # Change ggplot2 theme
    )
  8. Draw basic survival curves with ggsurvplot()

    master

    The primary function for visualization is ggsurvplot(). It takes a survfit object and the original data used for fitting. You can customize the appearance of censoring marks using censor.shape and censor.size.

    # Basic plot
    ggsurvplot(fit, data = lung)
    
    # Plot with customized censor marks
    ggsurvplot(fit, data = lung, censor.shape="|", censor.size = 4)
  9. Advanced customization of axes and risk tables

    master

    Use xlim and break.time.by to adjust the X-axis view without affecting the underlying survival estimates. For the risk table, risk.table.y.text.col = TRUE colors the text annotations, and risk.table.y.text = FALSE replaces text names with bars in the legend of the risk table.

    ggsurvplot(
       fit,                     # survfit object
       data = lung,             # data used to fit
       risk.table = TRUE,      # show risk table
       pval = TRUE,             # show p-value of log-rank test
       conf.int = TRUE,         # show confidence intervals
       xlim = c(0,500),         # present narrower X axis
       xlab = "Time in days",   # customize X axis label
       break.time.by = 100,     # break X axis in time intervals
       ggtheme = theme_light(), # customize plot and risk table with a theme
       risk.table.y.text.col = T, # colour risk table text annotations
       risk.table.y.text = FALSE # show bars instead of names in legend of risk table
    )
  10. Create highly customized survival plots with ncensor and median lines

    master

    For maximum customization, ggsurvplot() allows adding a number of censored subjects plot (ncensor.plot) and median survival pointers (surv.median.line).

    ggsurv <- ggsurvplot(
               fit,                     
               data = lung,             
               risk.table = TRUE,       
               pval = TRUE,             
               conf.int = TRUE,         
               palette = c("#E7B800", "#2E9FDF"),
               xlim = c(0,500),         
               xlab = "Time in days",   
               break.time.by = 100,     
               ggtheme = theme_light(), 
               risk.table.y.text.col = T,
               risk.table.height = 0.25, 
               risk.table.y.text = FALSE,
               ncensor.plot = TRUE,      # plot the number of censored subjects at time t
               ncensor.plot.height = 0.25,
               conf.int.style = "step",  # customize style of confidence intervals
               surv.median.line = "hv",  # add the median survival pointer.
               legend.labs = 
                 c("Male", "Female")    
            )
    ggsurv
  11. Customize ggsurvplot() survival curves

    master

    You can highly customize ggsurvplot() using several parameters to control the visual appearance of the survival curve and its associated tables:

    • size: Change line size.
    • palette: Custom color palettes (vector of colors).
    • conf.int: Add confidence interval (TRUE/FALSE).
    • pval: Add p-value of log-rank test (TRUE/FALSE).
    • risk.table: Show risk table (TRUE/FALSE).
    • risk.table.col: Color risk table by strata.
    • legend.labs: Change legend labels.
    • risk.table.height: Adjust the height of the risk table.
    • ggtheme: Change the ggplot2 theme (e.g., theme_bw(), theme_light()).
    • xlim: Set X axis limits (does not affect survival estimates).
    • xlab: Customize X axis label.
    • break.time.by: Set time intervals for X axis breaks.
    • risk.table.y.text.col: Color risk table text annotations.
    • risk.table.y.text: If FALSE, shows bars instead of names in the risk table legend.
    • ncensor.plot: Plot the number of censored subjects at time t.
    • ncensor.plot.height: Height of the censor plot.
    • conf.int.style: Customize confidence interval style (e.g., "step").
    • surv.median.line: Add median survival pointer ("hv").
    ggsurvplot(
      fit, 
      data = lung, 
      size = 1,                 
      palette = c("#E7B800", "#2E9FDF"),
      conf.int = TRUE,          
      pval = TRUE,              
      risk.table = TRUE,        
      risk.table.col = "strata",
      legend.labs = c("Male", "Female"),    
      risk.table.height = 0.25, 
      ggtheme = theme_bw(),
      xlim = c(0,500),
      xlab = "Time in days",   
      break.time.by = 100,
      risk.table.y.text.col = TRUE,
      risk.table.y.text = FALSE
    )
  12. Draw survival curves with ggsurvplot()

    master

    The ggsurvplot() function is the primary tool for drawing survival curves. It can include a 'number at risk' table, cumulative event tables, and cumulative censored subject tables. It accepts a survfit object and the original data used for fitting.

    require("survival")
    # Fit survival curves
    fit <- survfit(Surv(time, status) ~ sex, data = lung)
    
    # Basic plot
    ggsurvplot(fit, data = lung)
    
    # Plot with custom censor shape and size
    ggsurvplot(fit, data = lung, censor.shape="|", censor.size = 4)