gridExtra Colour different rows with tableGrob

前端 未结 1 1782
情歌与酒
情歌与酒 2020-12-06 11:52

I have a question regarding tableGrob/grid.table from the gridExtra package. Using the regular parameter settings, it is straightforward to colour alternate rows. However,

相关标签:
1条回答
  • 2020-12-06 12:25

    starting with v>=2.0.0 of gridExtra, grid.table is now based on gtable, and can be customised to deeper levels than in previous versions. The vignette has more examples, but for completeness here is an example illustrating how to highlight specific cells,

    g <- tableGrob(iris[1:4, 1:3])
    find_cell <- function(table, row, col, name="core-fg"){
      l <- table$layout
      which(l$t==row & l$l==col & l$name==name)
    }
    
    ind <- find_cell(g, 3, 2, "core-fg")
    ind2 <- find_cell(g, 2, 3, "core-bg")
    g$grobs[ind][[1]][["gp"]] <- gpar(fontsize=15, fontface="bold")
    g$grobs[ind2][[1]][["gp"]] <- gpar(fill="darkolivegreen1", col = "darkolivegreen4", lwd=5)
    grid.draw(g)
    

    Edit: the above function is easily "vectorised"

    find_cells <- function(table, row, col, name="core-fg"){
      l <- table$layout
      unlist(Map(function(r, c) which(((l$t-1) == r) & ((l$l-1) == c) & (l$name == name)), row, col))
    }
    
    modify_cells <- function(g, ids, gp=gpar()){
      for(id in ids) g$grobs[id][[1]][["gp"]] <- gp
      return(g)
    }
    
    ids <- find_cells(g, 1:3, c(3,2, 1), "core-fg")
    g <- modify_cells(g, ids, gpar(fontsize=15, fontface="bold"))
    
    grid.newpage()
    grid.draw(g)
    

    Note that in most cases it would make more sense to specify the parameters during the table construction,

    faces <- sample(1:4, size = prod(dim(iris[1:4, 1:2])), replace = TRUE)
    tt <- ttheme_default(core=list(fg_params=list(fontface=faces)))
    
    grid.table(iris[1:4, 1:2], theme=tt)
    

    0 讨论(0)
提交回复
热议问题