2

I am trying to make a figure that includes a table1 (here is my example table1: mtcars table1) and some plots using ggdraw.

library(htmlTable)
library(table1)
library(tibble)
library(Hmisc)
library(cowplot)
mtcars
table_mtcars <- table1(~cyl +disp + hp, data = mtcars)
table_mtcars
mtcars_plot <- ggplot(mtcars, aes(x = cyl, y = disp)) +
  geom_jitter()
mtcars_plot

mtcars_plot2 <- ggplot(mtcars, aes(x = cyl, y = hp)) +
  geom_jitter() +
  ggtitle('with hp')
mtcars_plot2

ggdraw() + 
  draw_plot(table_mtcars, x = 0, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot2, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))

Unfortunately, only the plots show up here: ggdraw example image. Is there a way to insert a table into a ggdraw image? Thank you.

  • 1
    Welcome to SO! Can you clarify how you made `table_mtcars`? I don't recognize the function you're using `table1()`. What package is it from? – Dan Adams Feb 08 '22 at 17:33
  • Thank you so much for responding! I have the packages library(htmlTable) library(table1) library(tibble) library(Hmisc) – Athena Nguyen Feb 08 '22 at 18:27
  • 2
    Ok - it might be tricky to incorporate an HTML table into the layout. Check out [this](https://stackoverflow.com/questions/60349028/how-to-add-a-table-to-a-ggplot) question for more. – Dan Adams Feb 08 '22 at 18:51
  • 1
    It looks like it's possible with {flextable} using `as_raster()` and then add it with the plots using {patchwork} – Dan Adams Feb 08 '22 at 19:01

1 Answers1

2

One option to achieve your desired result using cowplot and table1 would be to convert your table to a flextable via table1::t1flex which allows to follow the answer referenced by @DanAdams in his comment, i.e. converting the flextable to a raster image via flextable::as_raster and adding it to the plot grid as a grid::rasterGrob.

Note: I added some padding around the table by adjusting the width and height and the position. But you could set that as you like.

library(table1)
library(cowplot)
library(ggplot2)
library(magrittr)
library(flextable)

table_mtcars <- table1(~cyl +disp + hp, data = mtcars) %>% 
  t1flex() %>% 
  flextable::as_raster()

mtcars_plot <- ggplot(mtcars, aes(x = cyl, y = disp)) +
  geom_jitter()

mtcars_plot2 <- ggplot(mtcars, aes(x = cyl, y = hp)) +
  geom_jitter() +
  ggtitle('with hp')

ggdraw() + 
  draw_plot(grid::rasterGrob(table_mtcars), x = 0.025, y = .525, width = .45, height = .45) +
  draw_plot(mtcars_plot, x = .5, y = .5, width = .5, height = .5) +
  draw_plot(mtcars_plot2, x = 0, y = 0, width = 1, height = 0.5) +
  draw_plot_label(label = c("A", "B", "C"), size = 15,
                  x = c(0, 0.5, 0), y = c(1, 1, 0.5))

stefan
  • 90,330
  • 6
  • 25
  • 51