rcowplotgtpatchworkgtextras

Combine multiple gt tables to single one plot


With code below (edited basing on code from here) I generates two example tables with gt package:

library(tidyverse)
library(patchwork)
library(gt)

p1 <- mtcars %>% 
  head(5) %>% 
  gt()

p2 <- mtcars %>% 
  tail(5) %>% 
  gt()

# using wrap elements because this seems to be the answer to non-ggplot grobs e.g. #164 
wrap_elements(full = p1 | p2)
grid.arrange(p1, p2, ncol=2, top="Main Title")

Out:

Error in p1 | p2 : 
  operations are possible only for numeric, logical or complex types

I hope to combine them into one as for ggplot objects: p <- (p1 | p2) using patchwork package, but I didn't find an effective answer yet.

I also try to convert it to ggplot using as_ggplot() function:

library(bstfun)

mtcars %>%
  head(5) %>%
  gt() %>% 
  as_ggplot()

But it raises an error:

Error: '.assert_package' is not an exported object from 'namespace:broom.helpers'

Is it possible to do so? Thanks for your help at advance.

Reference:

R - combine two gt objects in a single page output


Solution

  • I can offer to you this solution:

    1. We take your data:

       p1 <- mtcars %>% 
          head(5) %>% 
          gt()
    
       p2 <- mtcars %>% 
          tail(5) %>% 
          gt()
    

    2. Let's save your tables into .png's:

        p1 %>%
           gtsave("p11.png", path = "Your_working_dir")
        p2 %>%
           gtsave("p12.png", path = "Your_working_dir")
    

    3. Let's combine your tables:

        library(cowplot)
        p111 <- ggdraw() + draw_image("p11.png", scale = 0.8)
        p112 <- ggdraw() + draw_image("p12.png", scale = 0.8)
        plot_grid(p111, p112)
    

    Our result:

    enter image description here