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

竞争风险分析:ggcuminc图添加P值及修改图例求助

竞争风险曲线的格式调整与信息添加方案

问题背景

我正在开展一项评估研究变量与竞争事件间竞争风险的项目,已编写如下代码生成图形:

cuminc(Surv(TIME,STATUS,type="mstate") ~ SEX, BASE) %>%
ggcuminc(outcome = c("1","2")) + xlim(0,90) + ylim(0,0.2) + add_risktable() + scale_x_continuous(breaks = seq(0, 90, by = 10), limits = c(0, 90)) +theme_classic() + theme(legend.position = 'bottom', legend.direction = "horizontal")

已生成对应图形,但在添加信息与格式调整时遇到两个问题:

  1. 需要在两条曲线末端分别添加变量名称(死亡、非死亡)及对应P值(0.12、0.25);
  2. 图例中的“1”“2”无法通过outcome参数的rename修改,需替换为“死亡”“非死亡”。

解决方案

1. 修改图例标签

直接在绘图代码后添加scale_color_discrete()(若曲线为填充样式则用scale_fill_discrete())指定自定义标签,替代默认的“1”“2”:

cuminc(Surv(TIME,STATUS,type="mstate") ~ SEX, BASE) %>%
ggcuminc(outcome = c("1","2")) + 
  xlim(0,90) + 
  ylim(0,0.2) + 
  add_risktable() + 
  scale_x_continuous(breaks = seq(0, 90, by = 10), limits = c(0, 90)) +
  # 新增:替换图例标签
  scale_color_discrete(labels = c("死亡", "非死亡")) +
  theme_classic() + 
  theme(legend.position = 'bottom', legend.direction = "horizontal")

2. 在曲线末端添加名称与P值

先提取竞争风险模型的结果数据,定位每条曲线的末端坐标,再用geom_text()添加自定义文本:

# 保存模型结果
cr_model <- cuminc(Surv(TIME,STATUS,type="mstate") ~ SEX, BASE)

# 提取曲线末端数据并生成文本内容
end_points <- broom::tidy(cr_model) %>%
  filter(outcome %in% c("1","2")) %>%
  group_by(outcome, stratum) %>%
  slice(n()) %>%
  ungroup() %>%
  mutate(label = case_when(
    outcome == "1" ~ paste0("死亡\nP=0.12"),
    outcome == "2" ~ paste0("非死亡\nP=0.25")
  ))

# 绘图并添加末端文本
cr_model %>%
ggcuminc(outcome = c("1","2")) + 
  xlim(0,90) + 
  ylim(0,0.2) + 
  add_risktable() + 
  scale_x_continuous(breaks = seq(0, 90, by = 10), limits = c(0, 90)) +
  scale_color_discrete(labels = c("死亡", "非死亡")) +
  # 新增:添加曲线末端文本
  geom_text(data = end_points, aes(x = time, y = estimate, label = label, color = stratum), 
            hjust = -0.1, vjust = 0.5, size = 3.5) +
  theme_classic() + 
  theme(legend.position = 'bottom', legend.direction = "horizontal")

说明:

  • hjust = -0.1 控制文本在曲线末端右侧的偏移量,可根据图形布局调整;
  • 若模型无分组(SEX为单组),可去掉stratum相关分组逻辑;
  • 若需自动提取P值而非手动输入,可使用cmprsk::competi_test(cr_model)获取结果后整合到label中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:29:53