如何用patchwork的inset_element调整插图大小并定位至右上角?
生存分析插图的大小调整与右上角定位问题
我有两张生存分析图,其中big图作为背景图,small图作为插图。请问如何调整该插图的大小?以及如何将其定位在背景图的右上角?
原绘图代码
library(survminer) library(survival) library(patchwork) fit <- survfit(Surv(time, status) ~ sex, data = lung) # Big plot big <- ggsurvplot( fit, size = 1, legend.labs = c("A", "B"), ylim = c(0, 1), linetype = "strata", break.time.by = 365, palette = c("#E7B800", "#2E9FDF"), risk.table = TRUE, risk.table.title = "No. at risk", risk.table.height = 0.2, fontsize = 6, tables.theme = theme_cleantable() ) # Small plot (inset) small <- ggsurvplot( fit, size = 1, legend.labs = c("A", "B"), legend = "none", ylab = "", ylim = c(0.7, 1), linetype = "strata", xlim = c(0, 365), break.time.by = 365, palette = c("#E7B800", "#2E9FDF"), fontsize = 6, tables.theme = theme_cleantable() )
我的尝试代码
big_plot <- big$plot / big$table + plot_layout(heights = c(3, 0.5)) small_plot <- small$plot combined <- big_plot + inset_element(small_plot, left = 0.2, bottom = 1, right = 0.95, top = 1, align_to = 'plot') ggsave("combined.pdf", combined)
解决方案
你当前的inset_element参数设置存在问题(bottom和top都设为1,导致插图高度为0,无法正常显示)。要实现插图的右上角定位与大小调整,只需修改inset_element的四个位置参数:
left/right:控制插图在背景图上的横向位置与宽度,取值范围为0(最左/最下)到1(最右/最上)bottom/top:控制插图在背景图上的纵向位置与高度
修改后的完整代码
library(survminer) library(survival) library(patchwork) fit <- survfit(Surv(time, status) ~ sex, data = lung) # Big plot big <- ggsurvplot( fit, size = 1, legend.labs = c("A", "B"), ylim = c(0, 1), linetype = "strata", break.time.by = 365, palette = c("#E7B800", "#2E9FDF"), risk.table = TRUE, risk.table.title = "No. at risk", risk.table.height = 0.2, fontsize = 6, tables.theme = theme_cleantable() ) # Small plot (inset) small <- ggsurvplot( fit, size = 1, legend.labs = c("A", "B"), legend = "none", ylab = "", ylim = c(0.7, 1), linetype = "strata", xlim = c(0, 365), break.time.by = 365, palette = c("#E7B800", "#2E9FDF"), fontsize = 6, tables.theme = theme_cleantable() ) # 组合主图与风险表 big_plot <- big$plot / big$table + plot_layout(heights = c(3, 0.5)) small_plot <- small$plot # 调整插图位置与大小:定位右上角 combined <- big_plot + inset_element( small_plot, left = 0.6, # 插图左边界位于背景图60%宽度处 bottom = 0.6, # 插图下边界位于背景图60%高度处 right = 0.95, # 插图右边界位于背景图95%宽度处 top = 0.95, # 插图上边界位于背景图95%高度处 align_to = 'plot' ) ggsave("combined.pdf", combined)
参数调整说明
- 若想让插图更大:缩小
left值、增大bottom值(比如left=0.5, bottom=0.5),保持right和top不变即可增加插图的宽高 - 若想让插图更靠近右上角:增大
left和bottom值(比如left=0.7, bottom=0.7),缩小插图在背景图上的覆盖范围
内容的提问来源于stack exchange,提问作者geek45
相关产品推荐
相关产品推荐

