Why does the legend disappear when there is only one interest group in ggcuminc? (R Shiny)

26 views Asked by At

In my R Shiny app, I have a reactive plot in which the risk group of interest can sometimes only have one value, and thus one curve on the plot is generated. When this happens, the legend also disappears and I would like it to stay.

rrfit <- tidycmprsk::cuminc(Surv(EFS.Years, EFS.eventID) ~ Risk, data = combined_data) %>%
    ggcuminc(outcome = 'Relapse',
    theme = theme_minimal(),
    size = 1,
    linetype_aes = TRUE) +
    labs(x = "Years", y = "Cumulative Incidence") +
    coord_cartesian(ylim = c(0,1)) +
    scale_color_manual(values = palette_vector) +
    scale_linetype_manual(values = linetype_vector) +
    scale_x_continuous(limits=c(0,10), breaks=seq(from=0, to=10, by=1)) +
    add_legend_title(title = paste(legend_vector1, "n:", sample_vector, collapse = "\n"))

How can I fix this?

1

There are 1 answers

0
stefan On

The issue is, that when there is only one category the model object returned by tidycmprsk::cuminc has no strata column and only if such a column is present will you get a legend as this column is mapped on the color and/or linetype aes by ggcuminc.

Hence, one option to achieve your desired result would be ensure that there is always a strata column in the tidy model data used by ggcuminc, e.g. you could use an if to check whether such a column is present and if not add one.

Using a minimal reproducible example based on the default example from ggcuminc:

library(ggplot2)
library(ggsurvfit)
library(tidycmprsk)

plot_cuminc <- function(.data) {
  mod <- tidycmprsk::cuminc(Surv(ttdeath, death_cr) ~ trt, .data)
  
  if (! "strata" %in% names(mod$tidy)) {
    mod$tidy$strata <- factor(unique(mod$data$trt))  
  }
  
  mod |> 
    ggcuminc(
      outcome = "death from cancer",
      theme = theme_minimal(),
      size = 1,
      linetype_aes = TRUE
    ) +
    labs(x = "Years", y = "Cumulative Incidence") +
    coord_cartesian(ylim = c(0, 1)) +
    #scale_color_manual(values = palette_vector) +
    #scale_linetype_manual(values = linetype_vector) +
    scale_x_continuous(
      limits = c(0, 10),
      breaks = seq(from = 0, to = 10, by = 1)
    )  
}

plot_cuminc(trial)


trial2 <- trial |> subset(trt == "Drug A")

plot_cuminc(trial2)