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

如何用ggplot2在Kaplan-Meier嵌入图中实现间断Y轴?

在Kaplan-Meier主图中实现带间断Y轴的嵌入图

我尝试在Kaplan-Meier(KM)主图中插入放大的嵌入图(当生存曲线极为相似时,便于更精准观察),这是当前众多期刊采用的做法。但创建带间断Y轴的嵌入图难度较大,尝试多种方法均未达到预期效果。

现有实现:创建主图与嵌入图

首先我创建了两个图:一个带风险表的主图,一个无坐标轴标签和风险表的嵌入图。

library(survival)
library(survminer)
library(ggh4x)
library(ggbreak)

# 拟合模型
sfit <- survfit(Surv(time, status) ~ sex, data = colon)

# 创建带风险表的主图
main_plot <- ggsurvplot(sfit, risk.table=TRUE)

# 创建嵌入图
inset_plot <- ggsurvplot(sfit, risk.table=FALSE, ylim = c(0.4,1), legend = "none", xlab ="", ylab = "")

# 设置嵌入图背景透明
inset_plot$plot <-  inset_plot$plot +
  theme(
    panel.background = element_rect(fill = "transparent",
                                    colour = NA_character_), # 避免绘制面板轮廓
    panel.grid.major = element_blank(), # 移除主网格线
    panel.grid.minor = element_blank(), # 移除次网格线
    plot.background = element_rect(fill = "transparent",
                                   colour = NA_character_), # 避免绘制图轮廓
    legend.background = element_rect(fill = "transparent"),
    legend.box.background = element_rect(fill = "transparent"),
    legend.key = element_rect(fill = "transparent")
  )

main_plot$plot <- main_plot$plot +
  annotation_custom(grob = ggplotGrob(inset_plot$plot ),   
                    xmin = 1.5,xmax=Inf,ymin = -0.05 ,ymax = 0.7)
main_plot

主图效果

需求:为嵌入图添加间断Y轴

关于ggplot2中间断轴的问题已有相关解决方案,但我尝试的两种方法均存在问题:

方法1:使用ggh4x的截断轴

问题在于线段标记未准确显示在Y轴上。

inset_plot$plot +
  annotate("segment", 
           x = c(-200, -100), xend = c(100, 200),
           y = c(0.425, 0.425), yend = c(0.45, 0.45)
           ) +
  coord_cartesian(clip = "off") +
  guides(y = guide_axis_truncated(
    trunc_lower = c(-Inf, 0.45), 
    trunc_upper = c(0.425, Inf)
  ))
#> 已存在坐标系。添加新坐标系将替换现有坐标系。

方法1错误效果

方法2:使用ggbreak包

这是实现ggplot2间断轴最简单的方案,但仅在单独绘图时生效,作为嵌入图插入后,间断Y轴消失,轴缩放也出现错误。

ggbreak_inset <- inset_plot$plot +
  scale_y_cut(c(0.4), which=c(1, 2), scales=c(10, 1), space = 0.1) +
  scale_y_continuous(breaks = c(0.6, 0.8, 1)) 
#> Y轴刻度已存在。添加新的Y轴刻度将替换现有刻度。
ggbreak_inset 

单独绘图时该方法有效,但插入主图后:

new_main_plot <- main_plot  # 复制主图
new_main_plot$plot <- new_main_plot$plot +
  annotation_custom(grob = ggplotGrob(ggbreak_inset ),   
                    xmin = 1.5,xmax=Inf, ymin = -0.05 ,ymax = 0.7)
new_main_plot  # 间断Y轴缺失,轴缩放错误

方法2错误效果

理想效果如下,如何用ggplot2在嵌入图中实现这种间断轴?
预期效果


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:35:16