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

ggsurvplot()中如何自定义标题至右上角?

问题描述

我能在ggsurvplot()中自定义p值的位置,但没法把标题调整到右上角。以下是我使用的代码:

ggsurvplot(fit, # survfit object with calculated statistics
           data = paad_GeneName, # data used to fit survival curves
           pval = TRUE, # show p-value of log-rank test
           pval.coord = c(1,0.07), # p-value location
           pval.size = 6.5, # adjust p-value size
           title.coord = c(1,0),
           legend.title = "", 
           legend = "none",
           xscale = "d_y", # convert time as days to years in x-axis
           break.x.by = 365.25, # break X axis in time intervals by years as integers
           xlab = "Time (years)", # customize X axis label
           palette = c("red","darkgreen"))

运行代码后生成了对应图像,请问有没有办法将标题调整至右上角?

解决方法

ggsurvplot()并没有内置的title.coord参数来调整标题位置,要把标题移到右上角,你可以用以下两种方法:

方法一:修改ggplot主题

先把ggsurvplot的结果保存为对象,再通过theme()调整标题的对齐方式:

# 保存生存曲线绘图结果
p <- ggsurvplot(fit, 
           data = paad_GeneName, 
           pval = TRUE, 
           pval.coord = c(1,0.07), 
           pval.size = 6.5, 
           legend.title = "", 
           legend = "none",
           xscale = "d_y", 
           break.x.by = 365.25, 
           xlab = "Time (years)", 
           palette = c("red","darkgreen"))

# 调整标题到右上角
p$plot <- p$plot + theme(plot.title = element_text(hjust = 1, vjust = 0))

# 展示图像
print(p)
  • hjust = 1 实现水平靠右对齐
  • vjust = 0 实现垂直靠上对齐,你可以根据需要调整这个值来微调上下位置

方法二:手动添加标题文本

如果不需要默认的标题样式,也可以用annotate()手动在右上角添加标题内容:

# 先关闭默认标题
p <- ggsurvplot(fit, 
           data = paad_GeneName, 
           pval = TRUE, 
           pval.coord = c(1,0.07), 
           pval.size = 6.5, 
           legend.title = "", 
           legend = "none",
           xscale = "d_y", 
           break.x.by = 365.25, 
           xlab = "Time (years)", 
           palette = c("red","darkgreen"),
           title = "")

# 手动添加右上角标题
p$plot <- p$plot + annotate("text", x = Inf, y = Inf, label = "你的标题内容", hjust = 1.1, vjust = 1.1, size = 5)

print(p)

x = Inf和y = Inf定位到图像右上角,hjust和vjust用来微调文本与边缘的距离,避免文本超出图像范围。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:35:26