Search code examples
rggplot2datatablepatchwork

How to automatically scale a table when it is combined with a ggplot using patchwork


I'm using patchwork to assemble a plot and a table. The trouble is my table has quite a few columns, and so some disappear off the side. I want the table to scale so that whole thing becomes smaller to fit the space. Here's a simplified example:

library(ggplot2)
library(patchwork)
library(ggpmisc)

# Make a wide dataframe for demo purposes
my_data <- mtcars
names(my_data) <- paste0(names(my_data), "_two")
my_data <- cbind(mtcars, my_data)

# 1. Create a scatter plot
my_plot <- ggplot(my_data, aes(mpg, disp)) + 
  geom_point() + 
  labs(title = "A Scatter Plot of mtcars")

# 2. Create a table plot
table_data <- head(my_data)
my_table_plot <- ggplot() +
  theme_void() +
  annotate(geom = "table", x = 1, y = 1, label = list(table_data))

# 3. Combine plots with patchwork and adjust aspect ratio
my_assembled <- my_plot / my_table_plot + 
  plot_layout(heights = c(3, 1))

# Show the assembled plot
print(my_assembled)

enter image description here

As above, I know I can change the aspect ratio with plot_layout(heights = c(3, 1)), for example. However, this just changes the space available for the table. It doesn't actually make the table or its text smaller. Any help would be great!


Solution

  • One approach could be to use flextable:gen_grob to convert a flextable object to a grob that patchwork can use, and resize automatically to fit:

    library(flextable)
    my_plot + gen_grob(flextable(table_data)) +
      plot_layout(heights = c(3, 1))
    

    enter image description here

    Another option, as discussed in a gt issue, would be to render the table as an image and then combine that in: https://github.com/rstudio/gt/issues/961