Search code examples
rggplot2survival

Change default legend in ggcompetingrisks to group-status combination


I have the following competing risk plot that I want to format. Competing risk plot of two events with randomised data

This is the example code for it.

set.seed(10) 
ftime <- runif(125, min = 0.1, max = 10)
fstatus <- factor(sample(rep(0:2, times = round(c(74/125, 40/125, 11/125) * 125)),
                         size = 125, replace = TRUE))
group <- factor(sample(rep(0:1, times = round(c(107/125, 18/125) * 125)),
                       size = 125, replace = TRUE))

cm <- cuminc(ftime = ftime, fstatus = fstatus, group = group)

ggcr <- ggcompetingrisks(cm,
                         censor = FALSE,
                         conf.int = FALSE,
                         multiple_panels = FALSE,
                         gnames = c("CIR Event1", "CIR Event2", "NRM Event1", "NRM Event2"),
                         xlim = c(0,10),
                         ylim = c(0, 1.0),
                         xlab = "Time (Years)",
                         ylab = "Cum. Risk",
                         title = "",
                         legend.title = "",
                         legend.fond = 16,
                         palette = c("red3", "royalblue3")
)


CIR_plot <- ggpar(ggcr + geom_line(linewidth = 1) + 
                    scale_y_continuous(label = c("0,00", "0,25", "0,50", "0,75", "1,00"),
                                       breaks = c(0.00, 0.25, 0.50, 0.75, 1.0)) +
                    scale_x_continuous(breaks = 0:10),
                  font.main = c(14),
                  font.x = c(14),
                  font.y = c(14),
                  font.caption = c(14), 
                  font.legend = c(12), 
                  font.tickslab = c(12))

I would like to change the legend so that I can see Event1 CIR (red continous), Event1 NRM (red dotted), Event2 CIR (blue continous) and Event2 NRM (blue dotted). I need to do this as a revision of my work, that's why I would like to change as little as I can on the existing plot. However, unfortunatley I haven't been able to find a solution for this in ggcompetingrisk/ggplot.

Is there an "easy to implement" solution for this?


Solution

  • One option to achieve your desired result would be to overwrite the mapping via aes(), i.e. map the interaction of group and event on both colour and linetype then set the colors and linetypes via scale_color_manual and scale_linetype_manual:

    library(survminer)
    library(cmprsk)
    
    CIR_plot +
      aes(
        x = time, y = est,
        color = paste(event, group),
        linetype = paste(event, group)
      ) +
      scale_color_manual(
        values = rep(c("red3", "royalblue3"), each = 2),
        name = NULL
      ) +
      scale_linetype_manual(
        values = rep(c("solid", "dotted"), 2),
        name = NULL
      )
    

    enter image description here