Search code examples
ggplot2graphcolorssurvival-analysis

Adding colors to cumulative incidence function and plot (ggcuminc) made by tidycmprsk


So using the example dataset trial, I want to create a cumulative incidence function of two competing events and give them each a color. The example is not great since you might not need colors for it but in my dataset the two outcomes have a distinct CIF and coloring is useful.

#Load data
data("trial", package = "tidycmprsk")

#make plot
cuminc(Surv(ttdeath, death_cr) ~ 1, trial) %>%
  ggcuminc(outcome = c("death from cancer", "death other causes")) +
  add_confidence_interval() +
  add_risktable() +
  scale_ggsurvfit()

Output enter image description here

Question

How to get two different colors for death from cancer and death from other causes? Tried to use this guide but couldn't find the answer.


Solution

  • Since this package is using ggplot, you could use ggplot_build to modify the layers of the plot and give them colors. You could add these by modifying both layers based on their group number like this:

    library(tidycmprsk)
    library(ggsurvfit)
    library(dplyr)
    data("trial", package = "tidycmprsk")
    
    #make plot
    p <- cuminc(Surv(ttdeath, death_cr) ~ 1, trial) %>%
      ggcuminc(outcome = c("death from cancer", "death other causes")) +
      add_confidence_interval() +
      add_risktable() +
      scale_ggsurvfit() 
    
    q <- ggplot_build(p)
    
    q$data[[1]] <- q$data[[1]] %>%
      mutate(colour = ifelse(group == 1, "red", "blue"))
    q$data[[2]] <- q$data[[2]] %>%
      mutate(colour = ifelse(group == 1, "red", "blue"),
             fill = ifelse(group == 1, "red", "blue"))
    
    q <- ggplot_gtable(q)
    plot(q)
    

    Created on 2023-11-06 with reprex v2.0.2