Chapter 15 Plotting flextable

A flextable can be drawn as a graphic, with R graphic devices, instead of being written in a document. Three functions take a flextable and draw it:

They all call gen_grob(), which turns the flextable into a grid graphical object (a grob). Call gen_grob() directly to get this grob, for example to add the table to a grid drawing or to a ggplot2 plot.

The caption set with set_caption() is not drawn, by design: a caption is an annotation of a document that points to a table. Once the table is drawn as a graphic, the document gives this graphic its own caption, as for any figure.

Use a device based on ‘systemfonts’, such as those of ‘ragg’, ‘svglite’ or ‘ggiraph’, so that fonts are found and text is measured correctly.

To illustrate, we build a dumbbell chart of Bundesliga team statistics paired with a matching flextable (adapted from the R Graph Gallery).

library(ggplot2)
library(patchwork)

dataset <- data.frame(
  team = c(
    "FC Bayern Munchen", "SV Werder Bremen", "Borussia Dortmund",
    "VfB Stuttgart", "Borussia M'gladbach", "Hamburger SV",
    "Eintracht Frankfurt", "FC Schalke 04", "1. FC Koln",
    "Bayer 04 Leverkusen"
  ),
  matches = c(2000, 1992, 1924, 1924, 1898, 1866, 1856, 1832, 1754, 1524),
  won     = c(1206,  818,  881,  782,  763,  746,  683,  700,  674,  669),
  lost    = c( 363,  676,  563,  673,  636,  625,  693,  669,  628,  447)
)
dataset$win_pct  <- dataset$won  / dataset$matches * 100
dataset$loss_pct <- dataset$lost / dataset$matches * 100
dataset$team <- factor(dataset$team, levels = rev(dataset$team))

The dumbbell chart:

pal <- c(lost = "#EFAC00", won = "#28A87D")
df_long <- reshape(dataset, direction = "long",
  varying = list(c("loss_pct", "win_pct")),
  v.names = "pct", timevar = "type",
  times = c("lost", "won"), idvar = "team"
)

p <- ggplot(df_long, aes(x = pct / 100, y = team)) +
  stat_summary(
    geom = "linerange", fun.min = "min", fun.max = "max",
    linewidth = .7, color = "grey60"
  ) +
  geom_point(aes(fill = type), size = 4, shape = 21,
    stroke = .8, color = "white"
  ) +
  scale_x_continuous(
    labels = scales::percent,
    expand = expansion(add = c(.02, .02))
  ) +
  scale_y_discrete(name = NULL, guide = "none") +
  scale_fill_manual(
    values = pal,
    labels = c(lost = "Lost", won = "Won")
  ) +
  labs(x = NULL, fill = NULL) +
  theme_minimal(base_size = 10) +
  theme(
    legend.position = "top",
    legend.justification = "left",
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_blank()
  )
p

And the flextable:

ft_dat <- dataset[, c("matches", "win_pct", "loss_pct", "team")]
ft_dat$team <- as.character(ft_dat$team)

ft <- flextable(ft_dat) |>
  border_remove() |>
  bold(part = "header") |>
  colformat_double(j = c("win_pct", "loss_pct"),
    digits = 1, suffix = "%") |>
  set_header_labels(
    team = "Team", matches = "GP",
    win_pct = "Won", loss_pct = "Lost") |>
  color(color = "#28A87D", j = "win_pct") |>
  color(color = "#EFAC00", j = "loss_pct") |>
  bold(j = c("win_pct", "loss_pct")) |>
  italic(j = "team") |>
  align(align = "right", part = "all") |>
  autofit()
ft

GP

Won

Lost

Team

2 000

60.3%

18.1%

FC Bayern Munchen

1 992

41.1%

33.9%

SV Werder Bremen

1 924

45.8%

29.3%

Borussia Dortmund

1 924

40.6%

35.0%

VfB Stuttgart

1 898

40.2%

33.5%

Borussia M'gladbach

1 866

40.0%

33.5%

Hamburger SV

1 856

36.8%

37.3%

Eintracht Frankfurt

1 832

38.2%

36.5%

FC Schalke 04

1 754

38.4%

35.8%

1. FC Koln

1 524

43.9%

29.3%

Bayer 04 Leverkusen

15.1 Drawing a table: plot()

plot() draws the table on the current graphic device, with a small margin around it.

plot(ft)

Arguments are passed to gen_grob() (see below), for example plot(ft, fit = "fixed") to keep the size of the table instead of fitting it to the device.

15.2 Exporting as an image: save_as_image()

save_as_image() writes the table in a PNG or SVG file, at its own size. The extension of path sets the format; SVG needs the package ‘svglite’.

save_as_image(ft, path = "table.png")
save_as_image(ft, path = "table.svg")
  • res sets the resolution of PNG files (200 by default);
  • expand adds space around the table, in pixels (10 by default).

15.3 Controlling the drawing: gen_grob()

gen_grob() returns the grob used by plot(), save_as_image() and wrap_flextable(). Its arguments set how the table fits in the space where it is drawn:

  • fit: "auto" (default) resizes the table to fit the space, "width" only fits its width, "fixed" keeps the size given by column widths and row heights;
  • scaling: "min" (default) reduces text, lines and images when the space is too small, "full" also enlarges them, "fixed" never changes them;
  • wrapping: if TRUE (default), text wraps into lines to fit the width of its cell;
  • autowidths: if TRUE (default), column widths are adjusted to the content;
  • just: position of the table in its space, as in grid::grid.layout().

The size of the table is given by dim() on the grob, in inches:

gr <- gen_grob(ft, fit = "fixed")
dim(gr)
# $width
# [1] 3.675752
# 
# $height
# [1] 4.856998

As any grob, it can be added to a ggplot2 plot, for example with annotation_custom():

ft_small <- flextable(head(mtcars[, c("mpg", "cyl", "wt")], 4)) |>
  theme_box() |>
  autofit()

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  annotation_custom(
    gen_grob(ft_small, fit = "fixed", just = c("right", "top")),
    xmin = 4, xmax = 5.4, ymin = 26, ymax = 34
  ) +
  theme_minimal(base_size = 10)

15.4 Combining with plots: wrap_flextable()

wrap_flextable() wraps a flextable as a patchwork-compliant patch, to combine it with ggplot2 plots using the +, |, and / operators of patchwork.

With the package ‘munch’, the table and the plots can share the same rich text: markdown in cells, titles, axes and legends (see chapter 6).

15.4.1 Basic usage

By default, the header is placed above the plotting area of the plot (its panel) and the body rows keep their natural height: the rows of the table are not aligned with the categories of the plot.

15.4.2 Aligning rows with a discrete y axis

With flex_body = TRUE, body rows stretch to share the height of the panel of the adjacent plot, so that each row is centered on its category of the y axis. Header and footer keep their size, above and below the panel.

wrap_flextable(ft, flex_body = TRUE, just = "right") +
  p +
  plot_layout(widths = c(1.1, 2))

Rows are placed as ggplot2 places the categories of a discrete axis, with an expansion of 0.6 at each end. If you change this expansion in the plot (for example scale_y_discrete(expand = expansion(add = 1))), give the same value to wrap_flextable(): wrap_flextable(ft, flex_body = TRUE, expand = 1).

15.4.3 Aligning columns with a discrete x axis

With flex_cols = TRUE, data columns stretch to share the width of the panel of the adjacent plot, so that each column is centered on its category of the x axis. Use n_row_headers to keep leading columns out of the panel, with their natural width.

cyl_mpg <- aggregate(mpg ~ cyl, mtcars, mean)

gg_bar <- ggplot(cyl_mpg, aes(factor(cyl), mpg)) +
  geom_col(fill = "#28A87D", width = 0.7) +
  labs(x = "Cylinders", y = "Mean MPG") +
  theme_minimal(base_size = 10)

wide <- data.frame(t(round(cyl_mpg$mpg, 1)))
names(wide) <- cyl_mpg$cyl

ft_cyl <- flextable(wide) |>
  bold(part = "header") |>
  align(align = "center", part = "all") |>
  autofit()
wrap_flextable(ft_cyl, flex_cols = TRUE) /
  gg_bar +
  plot_layout(heights = c(1, 4))

15.4.4 Layout options

15.4.4.1 Which part of the table goes in the panel: panel

With panel = "body" (the default), the body is in the panel, the header above it and the footer below it: this is what makes the alignment above possible. With panel = "full", the whole table is in the panel.

wrap_flextable(ft, panel = "full", flex_body = TRUE, just = "right") +
  p +
  plot_layout(widths = c(1.1, 2))

The header now takes the top of the panel: the table fills the height of the plot, but its rows are not aligned with the categories.

15.4.4.2 Horizontal position: just

When the table is narrower than its area, just places it on the "left" (default), on the "right" or at the "center".

wrap_flextable(ft, flex_body = TRUE, just = "right") | p

15.4.4.3 Size of the area: space

space sets who decides the size of the area of the table: patchwork or the table itself. The two plots below combine the same small table with the same scatter plot.

p_scatter <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  theme_minimal(base_size = 10)

With space = "free" (the default), patchwork ignores the size of the table and shares the width as between two plots, here half and half. The table keeps its natural size in its half, and leaves empty space next to it.

wrap_flextable(ft_small, space = "free") | p_scatter

With space = "fixed", the area of the table has exactly the size of the table, and the plot takes all the remaining width.

wrap_flextable(ft_small, space = "fixed") | p_scatter

The same applies to the height when plots are stacked with /. "free_x" frees only the width (the height follows the table), "free_y" only the height (the width follows the table). flex_body = TRUE implies "free_y", as body rows take the height of the plot, and flex_cols = TRUE implies "free_x".

15.4.5 Summary: placement and stretching

Two arguments set how the table relates to the panel of the plot:

  • panel sets where the table is placed: which part of it is aligned with the panel;
  • flex_body (and flex_cols for columns) sets whether rows stretch to fill the panel.
flex_body = FALSE flex_body = TRUE
panel = "body" body at the top of the panel, natural height rows aligned with the categories
panel = "full" table at the top of the panel, natural height table fills the height of the panel, not aligned

To align rows with a discrete axis, use panel = "body" (the default) with flex_body = TRUE.

15.5 Limitations

  • Hyperlinks are not drawn. Equations made with as_equation() are drawn with R >= 4.3 and the package ‘equatags’.
  • Devices that do not use ‘systemfonts’, such as png() or pdf(), may not find the fonts of the table: prefer the devices of ‘ragg’, ‘svglite’ or ‘ggiraph’.
  • Drawing a very large table is slow, as each cell is measured and laid out.