如何在ggsurvplot中插入图片?R语言生存分析绘图求助
在ggsurvplot中插入图片的两种实现方法
方法1:借助patchwork包组合组件
ggsurvplot的输出是一个包含多个ggplot对象的列表($plot对应生存曲线、$table对应风险表),可以用patchwork将外部图片与这些组件灵活拼接。
完整示例代码
library(survminer) library(survival) library(patchwork) library(png) library(grid) # 1. 生成生存分析结果与ggsurvplot对象 fit2 <- survfit(Surv(entry, futime, death) ~ 1, myeloma) p <- ggsurvplot(fit2, data = myeloma, ggtheme = theme_gray(), legend = "none", risk.table = TRUE) # 2. 读取并转换图片为grob对象(以内置Rlogo为例) img <- readPNG(system.file("png", "Rlogo.png", package="png")) img_grob <- rasterGrob(img, width = 0.2, height = 0.2) # 场景A:将图片插入生存曲线内部(右上角位置) surv_plot_with_img <- p$plot + annotation_custom(img_grob, xmin = max(myeloma$futime)*0.7, xmax = max(myeloma$futime), ymin = 0.8, ymax = 1) final_plot_inner <- surv_plot_with_img / p$table print(final_plot_inner) # 场景B:将图片放在整个图的上方 img_plot <- ggplot() + annotation_custom(img_grob) + theme_void() final_plot_top <- img_plot / (p$plot / p$table) print(final_plot_top)
方法2:用grid包直接绘制到绘图设备
如果不需要保留ggplot对象的组合关系,可以在绘制完ggsurvplot后,直接用grid包把图片叠加到绘图区域。
示例代码
library(survminer) library(survival) library(png) library(grid) # 生成并绘制ggsurvplot fit2 <- survfit(Surv(entry, futime, death) ~ 1, myeloma) p <- ggsurvplot(fit2, data = myeloma, ggtheme = theme_gray(), legend = "none", risk.table = TRUE) print(p) # 读取图片并绘制到指定位置(x/y为0-1的相对坐标) img <- readPNG(system.file("png", "Rlogo.png", package="png")) img_grob <- rasterGrob(img, x = 0.8, y = 0.9, width = 0.15, height = 0.15) grid.draw(img_grob)
关键说明
- ggsurvplot的核心组件(生存曲线、风险表)都是标准ggplot对象,可直接用ggplot的语法修改。
annotation_custom()通过xmin/xmax/ymin/ymax控制图片在ggplot中的位置和尺寸。patchwork的/运算符用于垂直拼接绘图元素,能快速实现多层布局。
内容的提问来源于stack exchange,提问作者CharlesLDN
相关产品推荐
相关产品推荐

