1

I'm looking for a good way to add a table to a ggplot object. So far, I've tried ggplot2::annotate, ggpmisc::geom_table, and flextable::flextable.

As discussed in another question, flextable will do the job, but it is very slow (~5-10 seconds per table). This makes it less than ideal for adding multiple tables to a ggplot object.

I tried ggplot2::annotate, thinking that I could just lay out the table using tab characters (\t) and newlines (\n). It turns out that the annotate function ignores the tab characters, so I don't get a table.

Next I tried ggpmisc::geom_table. This gives a layout pretty close to what I want, but for some reason, when the text is left justified, it always cuts off the right hand edge of the longest line.

Is there a better way to add tables to ggplot objects? Or a way to repair one of my failed attempts?

I've also had suggestions from reddit to try ggtable or tableGrob, but so far I've made even less progress getting either of those to produce a ggplot object.

Here's the code I used to generate the tables in the images:

library(ggplot2)
library(ggpmisc)
library(tibble)
library(flextable)

# ggplot2::annotate
annotate_table <- paste0(
  0,    '\t', 'ggplot2::annotate ignores tabs',                 '\n',
  1,    '\t', 'one',                                            '\n',
  2,    '\t', 'two',                                            '\n',
  7777, '\t', 'seven thousand seven hundred and seventy seven', '\n'
)
t_annotate <- ggplot() +
  annotate('text', x = 0, y = 0, label = annotate_table) +
  theme_void()
t_annotate

# ggpmisc::geom_table
my_df <- data.frame(
  a = c(0, 1, 2, 7777),
  b = c('ggpmisc::geom_table cuts off text', 'one', 'two', 'seven thousand seven hundred and seventy seven')
)
my_tibble <- tibble(x = 0, y = 0, tbl = list(my_df))
t_geom_table <- ggplot(my_df) +
  geom_table(
    data    = my_tibble,
    mapping = aes(x = 0, y = 0, label = tbl),
    table.hjust = 'left',
    table.colnames = FALSE,
    table.theme = ttheme_gtminimal
  ) +
  theme_void()
t_geom_table

# flextable::flextable
my_df <- data.frame(
  a = c(0, 1, 2, 7777),
  b = c('flextable::flextable is slow', 'one', 'two', 'seven thousand seven hundred and seventy seven')
)
my_ft <- flextable(my_df)
my_ft <- delete_part(my_ft, 'header')
my_ft <- border_remove(my_ft)
my_ft <- autofit(my_ft)
my_ft <- as_raster(my_ft)  # This line is very slow
t_flextable <- ggplot() +
  annotation_custom(grid::rasterGrob(my_ft)) +
  theme_void()
t_flextable
dryguy
  • 11
  • 3
  • Just a few minutes ago I collected some links in a comment [on this other question](https://stackoverflow.com/q/67742738/903061). Don't know if it will help, but some more examples at the very least. – Gregor Thomas May 28 '21 at 17:42

0 Answers0