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)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With