4

Consider this example

library(gridExtra)
library(grid)

d1 <- head(iris[,1:3]) %>% as_tibble()
d2 <- head(iris[,2:5]) %>% as_tibble()

grid.arrange(tableGrob(d1),
             tableGrob(d2))

which gives enter image description here

This is really nice but I am missing the titles of the dataframes! How can I add them to the picture automatically?

Thanks!

ℕʘʘḆḽḘ
  • 18,566
  • 34
  • 128
  • 235

2 Answers2

5

You can use ggplot,

library(ggplot2)

dd1 <- ggplot() + annotation_custom(tableGrob(d1)) + labs(title = 'd1')
dd2 <- ggplot() + annotation_custom(tableGrob(d2)) + labs(title = 'd2')
grid.arrange(dd1, dd2, nrow = 2)

enter image description here

Sotos
  • 51,121
  • 6
  • 32
  • 66
  • pretty nice!!! just a follow up. Assume I have dozens of small dataframes like this. Is there a way to use `marrangeGrob` with `tableGrob` so that I get a pdf with 4x4 charts on each page? – ℕʘʘḆḽḘ Jan 16 '19 at 12:49
  • I am not sure. I literally came across `annotation_custom` and `tableGrob` yesterday... – Sotos Jan 16 '19 at 12:52
  • ok thanks! do you know how to get rid of the gray background though? looks a bit weird! >) – ℕʘʘḆḽḘ Jan 16 '19 at 13:04
  • [This link will help](https://stackoverflow.com/questions/10861773/remove-grid-background-color-and-top-and-right-borders-from-ggplot2). Let me know If you run into any issues – Sotos Jan 16 '19 at 13:06
3

I would suggest adding a textGrob to the gtable,

library(magrittr)

add_title <- function(g, title, padding = unit(2,"mm"), lpos=1, ...){
  tg <- textGrob(title, ...)
  g %>%
    gtable::gtable_add_rows(heights = grobHeight(tg) + padding, pos = 0L) %>% 
    gtable::gtable_add_grob(tg, t=1,b=1,l=lpos,r=ncol(g))

}


grid.arrange(tableGrob(d1) %>% add_title('a) First title', gp=gpar(fontsize=14, fontface=4), hjust=0, x=0, lpos=2),
             tableGrob(d2) %>% add_title('b) Second title', gp=gpar(fontsize=14, fontface=4), hjust=0, x=0, lpos=2))