Legend on survival plot
Asked Answered
P

1

6

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)
Pinchbeck answered 13/7, 2014 at 15:27 Comment(0)
H
8

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

Hypocycloid answered 13/7, 2014 at 15:36 Comment(2)
This worked perfectly. I just needed to add lty=2:3 the example you gave me. Brilliant.Pinchbeck
The process looks so manual. How do you know that survfit and unique(group) will produce the same ordering of lines?Stephanistephania

© 2022 - 2024 — McMap. All rights reserved.