Adding text to a grid.table plot

To place text close to the table you’ll want to evaluate the table size first,

library(gridExtra)
d <- head(iris)
table <- tableGrob(d)

grid.newpage()
h <- grobHeight(table)
w <- grobWidth(table)
title <- textGrob("Title", y=unit(0.5,"npc") + 0.5*h, 
                  vjust=0, gp=gpar(fontsize=20))
footnote <- textGrob("footnote", 
                     x=unit(0.5,"npc") - 0.5*w,
                     y=unit(0.5,"npc") - 0.5*h, 
                  vjust=1, hjust=0,gp=gpar( fontface="italic"))
gt <- gTree(children=gList(table, title, footnote))
grid.draw(gt)

Edit (17/07/2015) With gridExtra >=2.0.0, this approach is no longer suitable. tableGrob now returns a gtable, which can be more easily customised.

library(gridExtra)
d <- head(iris)
table <- tableGrob(d)

library(grid)
library(gtable)

title <- textGrob("Title",gp=gpar(fontsize=50))
footnote <- textGrob("footnote", x=0, hjust=0,
                     gp=gpar( fontface="italic"))

padding <- unit(0.5,"line")
table <- gtable_add_rows(table, 
                         heights = grobHeight(title) + padding,
                         pos = 0)
table <- gtable_add_rows(table, 
                         heights = grobHeight(footnote)+ padding)
table <- gtable_add_grob(table, list(title, footnote),
                         t=c(1, nrow(table)), l=c(1,2), 
                         r=ncol(table))
grid.newpage()
grid.draw(table)

Leave a Comment