install.packages("survival")
install.packages("survminer")
install.packages("ggfortify")
library(survival)
library(survminer)
library(ggfortify)
使用{survival}中的数据lung,提取三个变量简化数据:# 数据
mydata <- lung[, c(2, 3, 5)]
summary(mydata)
km_fit <- survfit(Surv(time, status) ~ sex, data = mydata)
plot(km_fit,
lty = 5, # 线的类型
col = c("darkred", "forestgreen"), # 两条线分别的颜色
lwd = 2, # 线的宽度
xlab = "Time (months)",
ylab = "Survival Probability",
main = "Survival Curves")
如果想要更加精美的生存曲线,可以看看R包{survminer}和{ggfortify}。下面会一一介绍!
第二种,可以使用{survminer}包中的ggsurvplot():ggsurvplot(km_fit,
data = mydata,
risk.table = TRUE)
ggsurvplot(km_fit,
data = mydata,
fun = "pct",
linetype = "strata", # 按strata组别,使用不同线条类型
palette = c("firebrick", "steelblue"),
conf.int = TRUE,
pval = TRUE,
risk.table = TRUE,
risk.table.col = "strata", # 按strata组别,表格使用不同颜色
ggtheme = theme_bw())
第三个,使用{ggfortify}中的函数autoplot():autoplot(km_fit,
surv.linetype = "strata", # 线条类型按组别分
surv.size = 1,
conf.int = TRUE,
conf.int.fill = "grey",
censor.shape = "*", # 改变表示censor的形状
censor.size = 5, # 大小
ncol = 2,
xlab = "Time (months)",
ylab = "Survival Probability") +
theme_bw()
好啦,今天的内容就到这里。如果有帮助,记得分享给需要的人![1]. https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_surv.html
[2]. https://github.com/kassambara/survminer
[3]. https://cran.r-project.org/web/packages/survival/index.html
公众号核心成员担任SCI杂志Associate Editor!▌课程相关咨询可添加R师妹微信: kefu_rstats