Search code examples
rplotlegendsurvival-analysis

Legend on survival plot


Hi I am totally new to R. This is my first attempt at it. I am producing a survival plot broken down by age. I can't figure out how to specify colours for each age line and put it in a legend. Can anyone help?

require(survival)  # not loaded by default although installed by default
group <- age
kmsurvival1 <- survfit(Surv(as.numeric(time),event) ~ group)
plot(kmsurvival1, xlab="Time",ylab="Survival Probability", mark.time = F)

Solution

  • You just need to specify a vector of colors the same length as the number of lines (i.e. groups) in your plot. You could do this as

    N <- length(unique(group))
    plot(kmsurvival1, xlab="Time",ylab="Survival Probability", mark.time = F,
    col=1:N)
    legend(
      "topright",
      legend=unique(group),
      col=1:N,
      horiz=FALSE,
      bty='n')
    

    or you can manually specify the colors col=c('black','blue','red') (depending on how many colors you need).

    From the example in ?plot.survfit,

    library(survival)
    leukemia.surv <- survfit(Surv(time, status) ~ x, data = aml)
    plot(leukemia.surv, lty = 2:3,col=3:4)
    lLab <- gsub("x=","",names(leukemia.surv$strata))  ## legend labels
    legend(
      "top",
      legend=lLab,
      col=3:4,
      lty=2:3,
      horiz=FALSE,
      bty='n')
    

    enter image description here