2

What are your preferred techniques for combining a table with a plot in one image using R? I remember using tableGrob() and either patchwork or cowplot months ago but cannot remember the details.

This example uses the ggstatsplot package. I would like to add the correlation coefficients to the correlogram (correlation plot).

if (!('ggstatsplot' %in% installed_packages)) {
    devtools::install_github('https://github.com/IndrajeetPatil/ggstatsplot')
}
needed_pkgs <- setdiff(c('ggstatsplot', 'statsExpressions',
                       'dplyr', 'nnet', 'MASS'),
                       installed_packages)
if (length(needed_pkgs) > 0) {
    install.packages(needed_pkgs)
}

library(ggstatsplot)
library(statsExpressions)
library(dplyr)
library(nnet)
library(MASS)
utils::example(topic = birthwt, echo = FALSE)

# model
bwt.mu <-
    nnet::multinom(
        formula = low ~ .,
        data = bwt,
        trace = FALSE
    )

original_cols <- colnames(bwt)

bwt.mu_coefstats <- ggcoefstats(x = bwt.mu, output = "tidy") %>% 
    # skipping first row = intercept
    slice(2:n()) %>% 
    dplyr::filter(term %in% original_cols) %>% 
    arrange(desc(p.value)) %>% 
    dplyr::select(term, estimate, p.value)

# Correlogram
cor_plot_out <- 
    ggstatsplot::ggcorrmat(bwt %>% dplyr::select(low, lwt, age))

Want to combine

bwt.mu_coefstats

coefficients from statistical model

cor_plot_out

Correlogram

Rick Pack
  • 1,044
  • 10
  • 20

1 Answers1

2

The key elemnent is tableGrob() from gridExtra package!

We could use grid.arrange().

For the table use tableGrob() to create a table like the plot of a data frame. Then you can use it with grid.arrange() function.

library(gridExtra)

bwt.mu_coefstats <- tableGrob(
    bwt.mu_coefstats,
    theme = ttheme_default(
      base_size = 10,
      base_colour = "grey25",
      parse = T
    ),
    rows = NULL
  )

grid.arrange(cor_plot_out, bwt.mu_coefstats,
             heights = c(10, 4))

enter image description here

OR with patchwork:

library(patchwork)
cor_plot_out + bwt.mu_coefstats

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66