如何在网格中绘制ctree的结果?

How to plot the restults of ctree in grid?

绘图的结果可以正常排列在网格中。我目前通过在网格中绘制 party 包中 ctree 函数的结果而遇到问题。此问题与 6 年零 8 个月前 (Plot of BinaryTree (ctree, party) ignores plot option of par()) 的问题重复。选择 gridExtra 可以提供解决方案。但是,到目前为止,还没有针对此问题给出解决方案。考虑下面的例子。

library(party)
library(gridExtra)

#Create random dataframe
dfA <- data.frame(x=c(rnorm(50, 5), rnorm(50, 2)), 
                  y=c(rbinom(50, 1, .9), rbinom(50, 1, .1)))

#Duplicate dataframe
dfB <- dfA

#Plot in base R wit par (does not work)
par(mfrow = c(1, 2))
plot(party::ctree(y~x, data=dfA))
plot(party::ctree(y~x, data=dfB))

#Try to organize in a grid wit gridExtra (does not work)
treeA <- party::ctree(y~x, data=dfA)
treeB <- party::ctree(y~x, data=dfB)

grobA <- arrangeGrob(plot(treeA))
grobB <- arrangeGrob(plot(treeB))

grid.arrange(grobA, grobB, ncol=2)

Error in gList(list(wrapvp = list(x = 0.5, y = 0.5, width = 1, height = 1,  : 
                                    only 'grobs' allowed in "gList" 

arrangeGrob(plot(treeA))arrangeGrob(plot(treeB)) 也 return 一个错误说明 Error in vapply(x$grobs, as.character, character(1)) : values must be length 1, but FUN(X[[1]]) result is length 0

有人知道如何在网格中绘制 ctree 函数的结果吗?

提前致谢。

## grab the scene as a grid object
library(gridExtra)
library(gridGraphics)
library(grid)

list.to.pass <- list('plot(ctree(y~x, data=dfA))',
                     'plot(ctree(y~x, data=dfB))')
out<-list()
for (i in c(1,2)){
  print(i)
  
  formula(list.to.pass[[i]])
  
  out[[i]] <- grid.grab()
  
  print(out[[i]])
  dev.off()
}
grid.arrange(out[[1]], out[[2]], nrow = 1,ncol=2)

您将获得:

party 及其后续包 partykit 中的绘图在 grid 中实现,因此 par() 中的基本图形选项(例如 mfrow 执行不行。您可以使用 grid.layout() 来获得类似的结果。简单地这样做 grid 有点技术性,但代码应该不会太难理解:

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))

pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1))
plot(treeA, newpage = FALSE)
popViewport()

pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2))
plot(treeB, newpage = FALSE)
popViewport()

newpage = FALSE 参数的原因是默认情况下绘图是在新页面上绘制的,而不是添加到可能存在的绘图中。