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

purrr

#1

I'm trying to get patchwork to work within a function using grDevices::x11() so that my plots print in a new window. I can do it using grid but the former is not working correctly, it prints all the plots in the last window, see repex below:

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

#2

Hi platusresearch,

FYI, if you actually render this with the reprex package, the images show up as well! (Although, now that I've run it, I see that that might kind of defeat the point, since this is about getting new windows to open).

I had nine graphicsDevices windows open.

# 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
#> [[1]]
#> NULL
#> 
#> [[2]]
#> NULL
#> 
#> [[3]]
#> NULL

# 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))
#> [[1]]
#> 
#> [[2]]

Created on 2018-07-27 by the reprex package (v0.2.0.9000).