0

Reproducible example:

require(Survival)
require(survminer)
require(ggplot2)

set.seed(42)

a <- c(32,291,545, 44,3,792,352, 20,615,169, 61,156, 88,863,255, 33,132,5,
       63,8,964,831, 55,133, 12, 54,261,867, 17, 12,699,233,251,446, 43,223, 
       374, 75, 34, 69,120, 84,134,8,806,8, 48, 86,211, 2436, 61, 81, 87, 12, 
       838, 34, 17,141, 44,155,128,6, 29, 16, 16, 34,130,430,325, 41, 28, 53,
       32,291,545, 44,3,792,352, 20,615,169, 61,156, 88,863,255, 33,132,5,
       63,8,964,831, 55,133, 12, 54,261,867, 17, 12,699,233,251,446, 43,223,
       86, 54,3,630, 93,699, 25,746,6, 46, 22, 60,395,402,151, 26, 38,125, 
       75, 34, 69,120, 84,134,8,806,8, 48, 86,211, 2436, 61,
       191, 49, 59,6, 34, 56,2, 96, 422, 45, 70)

b <- sample(c("Alpha", "Beta", "Gamma"), length(a), replace = T)
c <- sample(0:1, length(a), replace = T)
df <- data.frame(a, b, c)

df$b <- factor(df$b, levels = c("Alpha", "Beta", "Gamma"))
avg <- survfit(Surv(time = a, event = c) ~ 1, data = df)
surv_b <- survfit(Surv(time = a, event = c) ~ b, data = df)
surv_comb <- list(surv_b, avg)

survminer::ggsurvplot_combine(
  surv_comb, 
  data = df,
  combine = TRUE,
  censor = FALSE,
  legend = "right",
  palette = c("orange", "steelblue", "seagreen", "black"),
  linetype = c(rep("solid",3), "dashed"),
  legend.title = element_blank(),
  legend.labs = c(levels(df$b), "avg")
)

The above code produces a chart with the legend duplicated as in the image below: ggsurvplot with duplicate legend

If I comment out the linetype argument in ggsurvplot, the legend is there only once - but I would really like to use the dashed linetype for the average to distinguish it from the other curves. Would anyone know how to fix the code so that it is like in the image but with the colour legend only and the correct linetypes, please?

Reader 123
  • 285
  • 1
  • 7
  • Does this answer your question? [How to merge color, line style and shape legends in ggplot](https://stackoverflow.com/questions/37140266/how-to-merge-color-line-style-and-shape-legends-in-ggplot) – andrew_reece Mar 09 '23 at 20:33

1 Answers1

1

Add labs() and use the same name for color and linetype:

p <- survminer::ggsurvplot_combine(
  surv_comb, 
  data = df,
  combine = TRUE,
  censor = FALSE,
  legend = "right",
  palette = c("orange", "steelblue", "seagreen", "black"),
  linetype = c(rep("solid",3), "dashed"),
  legend.title = element_blank(),
  legend.labs = c(levels(df$b), "avg")

p + labs(color = "lines", linetype = "lines")

enter image description here

andrew_reece
  • 20,390
  • 3
  • 33
  • 58