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
cor_plot_out
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))
OR with patchwork:
library(patchwork)
cor_plot_out + bwt.mu_coefstats