purrr::map 和 grDevices::x11 的拼凑效果不佳

patchwork not playing nicely with purrr::map and grDevices::x11

我正在尝试让 patchwork 在使用 grDevices::x11() 的函数中工作,以便我的绘图打印在新的 window 中。我可以使用 grid 来完成,但前者无法正常工作,它打印了最后一个 window 中的所有图,见下文:

# devtools::install_github("thomasp85/patchwork")
library(tidyverse)
library(patchwork)
library(grid)

x <- mtcars %>% rownames_to_column() 

p1 <- x %>% ggplot(aes(x = rowname, y = mpg)) + geom_col()
p2 <- x %>% ggplot(aes(x = rowname, y = cyl)) + geom_col()
p3 <- x %>% ggplot(aes(x = rowname, y = wt)) + geom_col()

xx2 <- xx1 <- xx <- list(p1 = p1, p2 = p2, p3 = p3)

# Function using grid - works
plot_list1 <- function(name, list1, list2, list3) {
  x11()
  grid.draw(rbind(ggplotGrob(list1[[name]]), 
                  ggplotGrob(list2[[name]]), 
                  ggplotGrob(list3[[name]]), size = "last"))
}

plot_list1("p1", xx, xx1, xx2) # works 
map(names(xx), ~plot_list1(name = ., xx, xx1, xx2))  # and works

# Function using patchwork works for one plot but misbehaves when used with map
plot_list <- function(name, list1, list2, list3) {
  x11()
  (list1[[name]] + list2[[name]] + list3[[name]] + plot_layout(ncol = 1))
}

# this works
plot_list("p1", xx, xx1, xx2) 
# this does not :(
map(names(xx)[1:2], ~plot_list(name = ., list1 = xx, list2 = xx1, list3 = xx2))  

Thomas 提供的答案:https://github.com/thomasp85/patchwork/issues/68

plot_list <- function(name, list1, list2, list3) {

 p <- list1[[name]] + list2[[name]] + list3[[name]] + plot_layout(ncol = 1)

  x11()
  plot(p)
}

# now works
walk(names(xx)[1:2], ~plot_list(name = ., list1 = xx, list2 = xx1, list3 = xx2))