如何从 R 中的 ggcoxdiagnostics dfBeta 输出中提取单个图形?

How do I extract an individual graph from ggcoxdiagnostics dfBeta output in R?

运行 ggcoxdiagnostics 为多变量 coxph 回归模型生成 dfBeta 图。

require(survival)
require(survminer)

# Dummy data
set.seed(100)
permth_int <- seq(10)
mortstat   <- c(rep(1,9),0)
age        <- runif(10,50,70)
sex        <- sample(seq(2),10,replace=T)
ill        <- sample(seq(3),10,replace=T)

# Create survival object
SO         <- Surv(permth_int,mortstat==1)

# Cox regression
model <- coxph(SO ~ age + sex + ill)   

# Produce diagnostics plot
plots <- ggcoxdiagnostics(model, type = "dfbeta",
                 linear.predictions = FALSE, ggtheme = theme_bw())
plots

它生成一个包含多个图形的网格。我想一次引用这些图表。有没有一种简单的方法可以从 ggcoxdiagnostics 生成的对象中获取单个图形?

这有点棘手,因为 ggcoxdiagnostics 正在调用 ggplot 并对模型中的预测变量使用分面包装。我借鉴了 https://whosebug.com/users/419994/sandy-muspratt in an answer to 并开发了以下解决方案:

# You'll need these libraries
library(gtable)
library(grid)

# Get a ggplotGrob from your plots object
gr <- ggplotGrob(plots)

# Visually examine the layout grid that `plots` is drawn to
gtable_show_layout(gr)

# The first plot (`age` facet) occupies the first 6 columns of the grid 
gr1 <- gr[, 1:6]

# You'll need column 2 for the second and third plots, as it contains the y-axis label
gr2 <- gr[, c(2, 7:10)]

# Third plot:
gr3 <- gr[, c(2, 11:15)]

# Draw the third plot
grid.newpage()
grid.draw(gr1)

# Draw the second plot
grid.newpage()
grid.draw(gr2)

# Draw the second plot
grid.newpage()
grid.draw(gr3)