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

如何让ggsurv()绘图的图例顺序匹配因子水平顺序?

解决ggsurv()绘图图例顺序与因子水平不一致的问题

在使用ggsurv()绘制生存曲线时,若图例顺序和你预设的因子水平顺序不符,可通过以下两种方法调整:

方法1:直接指定legend.order参数

ggsurv()函数本身提供了legend.order参数,你可以直接传入因子的水平顺序(或从数据框中获取预设的因子水平),让图例顺序与之一致:

library(survival)
library(survminer)

df <- data.frame(time_to_event = c(2,3,5,7,10),
                 event = c(1,0,1,0,0),
                 grp = factor(c('A','B','A','B','B'),levels=c('A','B')))
                 
fit <- survfit(Surv(time_to_event, event==1) ~ grp, data = df)

# 使用预设的因子水平指定图例顺序
ggsurv(fit, legend.order = levels(df$grp))

方法2:通过ggplot的scale函数调整

由于ggsurv()返回的是ggplot对象,你可以叠加scale_color_discrete()或scale_fill_discrete()函数,通过limits参数强制图例遵循因子水平顺序:

ggsurv(fit) +
  # 调整颜色图例顺序
  scale_color_discrete(limits = levels(df$grp)) +
  # 调整填充图例顺序(若图中有填充元素)
  scale_fill_discrete(limits = levels(df$grp))

两种方法都能让图例顺序严格匹配你在grp列中设置的因子水平顺序,其中用levels(df$grp)获取因子水平的方式更灵活,后续修改因子水平时无需手动调整参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:38:21