You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot为survfit生成的autoplot生存曲线添加线标签问询

survfit对象autoplot生存曲线添加就地标签解决方案

核心逻辑:survminer::autoplot输出的是标准ggplot对象,所有绘图所需数据都存储在返回对象的$data属性中,直接调用该数据集即可避免geom系列函数找不到变量的问题。

前置依赖包

需提前安装加载以下包:

  • survival
  • survminer
  • ggplot2
  • ggrepel(可选,用于避免标签重叠)
  • directlabels(可选,适配你之前的尝试方向)

方案1:ggrepel实现曲线右端标签(推荐)

代码示例:

# 生成基础绘图对象
p <- autoplot(survfit(Surv(time, status) ~ sex, data = lung), fun = 'event')

# 提取每个分组最右侧的节点用作标签锚点
label_data <- p$data |> 
  dplyr::group_by(strata) |> 
  dplyr::slice_max(time, n = 1) |> 
  dplyr::ungroup()

# 添加标签并隐藏原有图例
p +
  geom_text_repel(
    data = label_data,
    aes(x = time, y = estimate, label = strata),
    nudge_x = 15, # 可根据画布宽度调整偏移量,避免标签溢出
    show.legend = FALSE
  ) +
  theme(legend.position = "none")

方案2:修复directlabels调用问题

你之前调用directlabels失败是因为没有指定数据来源,指定为p$data即可正常运行:

library(directlabels)

p <- autoplot(survfit(Surv(time, status) ~ sex, data = lung), fun = 'event')

p +
  geom_dl(
    aes(label = strata), 
    method = list(dl.trans(x = x + 20), "last.points"),
    data = p$data # 核心:指定从ggplot内置数据取数
  ) +
  theme(legend.position = "none")

自定义标签位置

如果需要把标签放在曲线左侧/中间任意位置,仅需修改锚点数据的筛选逻辑即可,比如要放在时间点为400的位置:

label_data <- p$data |> 
  dplyr::group_by(strata) |> 
  dplyr::filter(abs(time - 400) == min(abs(time - 400))) |> 
  dplyr::ungroup()

内容的提问来源于stack exchange,提问作者waterproofpatch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:27:01