0

It's my first question on SO. Hopefully it will be enough detail:

I've made a Kaplan-Meier plot and would like to add a legend, however I am not having much luck with it. I know how to make a legend when you know which line is representative of it's respective category. Unfortunately since I'm using a large data set I don't know which line is which, and therefore am having a hard time creating the legend manually. Is there any way R can infer which category is which colour on the following graph? (The current selections aren't right in the legend, I was just guessing)

    kmsurv1 <- survfit(Surv(as.numeric(time),hydraulic)~type)
# Specify axis options within plot() 
plot(kmsurv1, col=c(1:12), main="Hydraulic Breakdown of Vehicles", sub="subtitle", xlab="Time", ylab="Probability of Being Operational", xlim=c(15400, 16500),ylim=c(.6,1.0))
legend("bottomleft", inset = 0, title = "Vehicle Type",legend= c("Hitachi Backhoe","Transport Trucks", "Water Trucks","Cat D8 Dozers", "D10 Dozers")
       ,fill = c(1:12), horiz=TRUE)

enter image description here

M.D
  • 38
  • 1
  • 6

2 Answers2

1

I'm assuming you are using the survival package. The package document specifies that with print(obj), the order of printout is the order in which they plot. You can then extract those names with rownames(summary(sfit)$table). Just make sure that the colors you choose are in the same order in the plot and legend lines. Here's an example:

library(survival)
sfit <- survfit(Surv(start, stop, event) ~ sex, mgus1, subset=(enum==1))
print(sfit) # the order of printout is the order in which they plot
plot(sfit, col=1:4)
legend("topleft",legend=rownames(summary(sfit)$table),col=1:4, lty=1)

enter image description here

Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56
0

I found an extremely easy answer from: http://rpubs.com/sinhrks/plot_surv

    install.packages('ggfortify')
    install.packages("ggplot2")
    library(ggplot2)
    library(ggfortify)

    fit <- survfit(Surv(as.numeric(time),hydraulic)~type, data = mydata)
autoplot(fit,xlim = c(15000,16500))

My Answer

Thank you to https://stackoverflow.com/users/3396821/mlavoie for pointing me in the right direction.

Community
  • 1
  • 1
M.D
  • 38
  • 1
  • 6