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

我是研究僧i 提交于 2020-01-05 10:06:11

问题


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):

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]))

回答1:


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)



来源:https://stackoverflow.com/questions/31506294/gtable-put-a-black-line-around-all-cells-in-the-table-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!