Applied Epi Community

Combining a ggplot and table in R

Question from @amyplimmer :

Hi all,

We use ggplot geom_segment to produce patient movement timelines (TICL charts) like the one below. Once the plot is in word once the plot is in word, I have been manually adding on tables of extra information like the one on the right-hand side below. Is there a way to code for a side table like this in R please? A quick google has shown me it has been done with forest plots (Forest plots in R (ggplot) with side table | R-bloggers). Would it work with plots like the ones below?

Yes there is a way to do this, with the package cowplot. There are three steps:

  1. Create the plot as normal with ggplot and the table with e.g. flextable.
  2. Convert the flextable to a ggplot with grid::raster_grob()
  3. Combine the plot and the table into a single figure with cowplot::plot_grid(), specifying nrow = 1 and ncol = 2 in the function arguments.

The code to convert the flextable to a ggplot takes a little working out, so I have included an example below.

Say for example your timeline plot is called mytimelineplot and your table is called mytimelinetable:

# Convert flextable to ggplot image for saving:
mytimelinetablegg <- ggplot() +
  theme_void() +
                    xmin = -Inf,
                    xmax = Inf,
                    ymin = -Inf,
                    ymax = Inf)

A raster is an image that is split up into its component parts, which makes it easier to convert to other formats.
The xmin, ymin, xmax and ymax arguments are for setting the position of the table in the ggplot space.
Setting them to infinity allows the table to take up the whole plotting space.

Then to combine the plot and converted table:

# Put the figure and table together:
final_figure <- cowplot::plot_grid(mytimelineplot,
                                                    nrow = 1,
                                                    ncol = 2,
                                                    rel_heights = c(1, 1))

This function allows you to specify the way that tables and figures are presented together, by specifying the number of rows, columns and the relative height of the two figures.

1 Like

Such a common scenario! Thanks @amy.mikhail for the detailed reply.
More information on the {cowplot} package and another example can be found in the Epi R Handbook here: 31 ggplot tips | The Epidemiologist R Handbook