4  {ggplot2} and {gt} assembly

When creating a series of outputs, it is desirable to keep them visually unified. Is it possible to combine plots and tables in a single figure? Yes, it is - including tables produced with the {gt} package. We will only need a small trick to convert a gt table to a grob, which we can then combine with a plot created with the famous {ggplot2} package.

1. Make a plot

Here, we will create a simple violin plot to visualize the distribution of measured δ13C across countries in this data set.

p_violin <- ggplot(dat_vegetation, aes(x = country_label, y = delta)) +
  geom_violin(colour = "black", fill = "#005C55FF") +
  labs(x = "",
       y = expression(delta ^13 ~ C)) +
  theme_classic() +
  theme(
    plot.margin = margin(0, 0, 0, 0),
    plot.background = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black", linewidth = 0.75),
    axis.ticks.y = element_line(colour = "black", linewidth = 0.75),
    axis.ticks.x = element_blank(),
    axis.text = element_text(colour = "black", size = 17),
    axis.title = element_text(colour = "black", size = 19),
    aspect.ratio = 0.75
  )
Figure 4.1

2. Make a gt table

gt_for_plot <- dat_vegetation |>
  group_by(country) |>
  summarize(
    mean_d = mean(delta),
    median_d = median(delta)
  ) |>
  gt() |>
  tab_spanner(columns = contains("_d"), label = md("&delta;^13^C")) |>
  cols_label(
    country = "Country",
    mean_d = "Mean",
    median_d = "Median"
  ) |>
  # decimal places control
  fmt_number(columns = contains("_d"), decimals = 2) |> 
  # column labels and spanners in bold font face
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_column_labels(everything())
  ) |>
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_column_spanners(spanners = everything())
  ) |> 
  tab_options(table.font.size = 11)
Country
δ13C
Mean Median
Argentina −27.62 −27.45
Democratic Republic of the Congo −34.11 −34.35
Kenya −19.80 −23.30
Mongolia −25.28 −24.75

3. Convert gt table to a grob (required by {patchwork}), which requires new dependencies:

library(magick)
library(ggplotify)

With a small function, we can first save the gt table as an PNG image and with help of the {ggplotify}, further conversion into a grob is possible:

as_grob_gt <- function(x) {
  tmp <- tempfile(fileext = ".png")
  gtsave(x, filename = tmp)
  img <- magick::image_read(tmp)
  
  # Returns a ggplot grob for patchwork
  return(ggplotify::as.grob(img)) 
}

4. Assemble plot and table into a single figure

As mentioned above, we will use the {patchwork} package for a final plot-table assembly.

library(patchwork)

Once gt table is converted to a grob

gt_grob_patchwork <- as_grob_gt(gt_for_plot)

we can treat it as e.g., another ggplot2 figure and with help of {patchwork}’s syntax, control relative positions of plot and table as well as their alignment

p_violin / gt_grob_patchwork
Figure 4.2