ggsurvplot技术问询:风险人数图例颜色匹配与线条替代需求
解决ggsurvplot生存曲线风险表格颜色同步与线条替代图例问题
问题1:同步风险表格与曲线的颜色
你当前仅修改了生存曲线(p$plot)的颜色映射,但风险表格(p$table)的颜色未同步调整,导致两者不一致。只需给p$table添加相同的颜色映射即可:
# 原代码中定义颜色和线型 colors <- rep(c("red", "red","blue","blue")) lines <- rep(c("solid","dashed","solid", "dashed")) # 修改plot的颜色和线型 p$plot <- p$plot + scale_linetype_manual(values = lines) + scale_colour_manual(values = colors) # 同步风险表格的颜色 p$table <- p$table + scale_colour_manual(values = colors)
问题2:用线条替代风险表格的图例(y轴文本)
要将风险表格左侧的分组文本替换为对应线型/颜色的线条,可通过隐藏原y轴文本、添加自定义线段的方式实现:
# 获取分组名称 strata_names <- names(fit$strata) # 构建线条数据:对应每个分组的y位置、线型、颜色 line_data <- data.frame( y = seq_along(strata_names), x_start = -0.1, x_end = 0, linetype = lines, color = colors ) # 修改风险表格:隐藏原y轴文本,添加线条 p$table <- p$table + theme(axis.text.y = element_blank()) + geom_segment(data = line_data, aes(x = x_start, xend = x_end, y = y, yend = y, linetype = I(linetype), color = I(color))) + xlim(-0.1, max(p$table$data$time)) # 调整x轴范围,确保线条显示
完整可运行代码
n <- 200 # 补充定义n的值 subjid <- 1:n status_os <- sample(c(0,1), n, replace = TRUE) time_os <- ifelse(status_os==0, rnorm(n,mean=365, sd=30), rnorm(n, mean=180, sd=30)) groupe <- sample(c(1,2), n, replace=TRUE) mutation <- sample(c(1, 0), n, replace=TRUE) data <- data.frame(Identifiant=subjid, status_os=status_os, time_os=time_os, groupe=groupe, mutation=mutation) fit <- survfit(Surv(time_os, status_os)~groupe+mutation, data=data) p <- ggsurvplot(fit, data = data, break.time.by = 12, risk.table = "nrisk_cumevents", legend.title = "", legend = c(0.2, 0.2), linetype = "strata", risk.table.y.text=TRUE, break.x.by = 50) colors <- rep(c("red", "red","blue","blue")) lines <- rep(c("solid","dashed","solid", "dashed")) # 同步曲线和风险表格的颜色、线型 p$plot <- p$plot + scale_linetype_manual(values = lines) + scale_colour_manual(values = colors) p$table <- p$table + scale_colour_manual(values = colors) # 用线条替代风险表格的y轴文本 strata_names <- names(fit$strata) line_data <- data.frame( y = seq_along(strata_names), x_start = -0.1, x_end = 0, linetype = lines, color = colors ) p$table <- p$table + theme(axis.text.y = element_blank()) + geom_segment(data = line_data, aes(x = x_start, xend = x_end, y = y, yend = y, linetype = I(linetype), color = I(color))) + xlim(-0.1, max(p$table$data$time)) # 合并绘图 p$plot <- p$plot / p$table + plot_layout(ncol = 1, heights = c(2, 1)) # 查看结果 print(p$plot)
说明
- 颜色同步:通过给
p$table添加与p$plot相同的scale_colour_manual,确保风险表格的文本颜色和曲线颜色一致。 - 线条替代图例:利用
geom_segment在风险表格左侧绘制对应线型和颜色的线段,同时隐藏原y轴文本,实现用线条标识分组的效果。
内容的提问来源于stack exchange,提问作者Guillaume
相关产品推荐
相关产品推荐

