Search code examples
rgridextrar-gridgtable

gtable: Put a black line around all cells in the table body


I'm trying to put a relatively heavy line (say lwd = 2 size) around the body of a table using gridExtra. Here's a MWE slightly modified from this documentation page. gtable is doing the work under the hood but the documentation for gtable is thin; looking at the code didn't help much.

g <- tableGrob(iris[1:4, 1:3], rows = NULL)
separators <- replicate(1, 
    segmentsGrob(x1 = unit(0,"npc")), 
    simplify=FALSE)
g <- gtable::gtable_add_grob(g, grobs = separators, 
    t = 1, b = nrow(g), l = 1)
g <- gtable::gtable_add_grob(g, grobs = separators, 
    t = 1, b = nrow(g), r = 3) # error: no default for l
grid.draw(g)

I'm trying to get an effect like this (different data):

sample

The 2nd call to gtable::gtable_add_grob gives an error, so obviously my simple notion that r = 3 will put the line on the right of the 3rd column is naive. Any suggestions as to how to get a heavier line around the body of the table? If I can grok the idea for the left and right edges I assume the top and bottom lines can be drawn analogously.

Side note: gridExtra was recently revised to use gtable. Previously I had made graphics like the one above with commands similar to those below; I'd like to get pretty close to the same settings if possible (the new method has rows alternating in grey level, that's nicer; I'm really after the old show.box feature).

myt <- gridExtra::tableGrob(aov1, show.box = TRUE,
                show.rownames = TRUE, show.colnames = TRUE,
                show.csep = TRUE, show.rsep = TRUE,
                separator = "black", gp = grid::gpar(cex = table[3]))

Solution

  • You could add a rectGrob spanning all the cells you want caged,

    library(gridExtra)
    library(gtable)
    library(grid)
    g <- tableGrob(iris[1:4, 1:3])
    g <- gtable::gtable_add_grob(g, 
                                 grobs = rectGrob(gp=gpar(fill=NA, 
                                                          lwd=2)), 
                                 t = 2, b = nrow(g), l = 2, r = ncol(g))
    grid.newpage()
    grid.draw(g)
    

    enter image description here