R - 从变量中推断传奇细节

时间:2015-12-09 23:08:03

标签: r plot

这是我关于SO的第一个问题。希望它足够详细:

我已经制作了一个Kaplan-Meier情节并且希望添加一个传奇,但是我没有太多运气。当你知道哪条线代表它的相应类别时,我知道如何制作一个传奇。不幸的是,因为我使用的是大型数据集,所以我不知道哪条线是哪条,因此很难手动创建图例。 R有什么方法可以推断出哪个类别是下图中的哪种颜色? (目前的选择在图例中并不正确,我只是在猜测)

    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

2 个答案:

答案 0 :(得分:1)

我假设您使用的是survival套餐。包文档指定使用print(obj)时,打印输出的顺序是它们绘制的顺序。然后,您可以使用rownames(summary(sfit)$table)提取这些名称。只需确保您选择的颜色在plotlegend行中的顺序相同。这是一个例子:

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

答案 1 :(得分:0)

我发现了一个非常简单的答案: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

感谢https://stackoverflow.com/users/3396821/mlavoie指出我正确的方向。