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

时间:2018-03-05 18:04:33

标签: r ggplot2 survival-analysis cox-regression

运行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生成的对象中获取单个图形?

1 个答案:

答案 0 :(得分:1)

这有点棘手,因为ggcoxdiagnostics正在调用ggplot并对模型中的预测变量使用构面包装。我在https://stackoverflow.com/users/419994/sandy-muspratt的答案中借用了Extract single plot from ggplot with facet_grid并制定了以下解决方案:

# 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)