Athena Nguyen
Athena Nguyen

Reputation: 31

R: Add a table1 to ggdraw figure

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.

Upvotes: 2

Views: 597

Answers (1)

stefan
stefan

Reputation: 125053

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

Upvotes: 2

Related Questions