Change Text Color for Cells using TableGrob in R

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

Is there a way to individually change the color of the text of a cell when using tableGrob and ggplot2? For instance in the code below it'd be great if the cell with 1 could be blue and the cell with 2 could be red, with 3:8 all black.

library(ggplot2) library(grid) mytable = as.table(matrix(c("1","2","3","4","5","6","7","8"),ncol=2,byrow=TRUE)) mytable = tableGrob(mytable,gpar.coretext = gpar(col = "black", cex = 1)) mydf = data.frame(x = 1:10,y = 1:10) ggplot( mydf, aes(x, y)) + annotation_custom(mytable)

Thanks!

回答1:

Much to my disappointment, this does not seem to be easy. The tableGrob function calls makeTableGrobs to layout the grid object and returns a fully calculated gTree structure. It would be nice if you could intercept that, change some properties, and continue on; unfortunately the drawing gets done with gridExtra:::drawDetails.table and that function insists on calling makeTableGrobs again, essentially killing any opportunity for customization.

But it's not impossible. Basically we can create our own version of drawDetails.table that doesn't do the reprocessing. Here's the function from gridExtra with one added if statement at the beginning.

drawDetails.table <- function (x, recording = TRUE)  {     lg <- if(!is.null(x$lg)) {         x$lg     } else {         with(x, gridExtra:::makeTableGrobs(as.character(as.matrix(d)),          rows, cols, NROW(d), NCOL(d), parse, row.just = row.just,          col.just = col.just, core.just = core.just, equal.width = equal.width,          equal.height = equal.height, gpar.coretext = gpar.coretext,          gpar.coltext = gpar.coltext, gpar.rowtext = gpar.rowtext,          h.odd.alpha = h.odd.alpha, h.even.alpha = h.even.alpha,          v.odd.alpha = v.odd.alpha, v.even.alpha = v.even.alpha,          gpar.corefill = gpar.corefill, gpar.rowfill = gpar.rowfill,          gpar.colfill = gpar.colfill))     }     widthsv <- convertUnit(lg$widths + x$padding.h, "mm", valueOnly = TRUE)     heightsv <- convertUnit(lg$heights + x$padding.v, "mm", valueOnly = TRUE)     widthsv[1] <- widthsv[1] * as.numeric(x$show.rownames)     widths <- unit(widthsv, "mm")     heightsv[1] <- heightsv[1] * as.numeric(x$show.colnames)     heights <- unit(heightsv, "mm")     cells = viewport(name = "table.cells", layout = grid.layout(lg$nrow +          1, lg$ncol +        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!