在R中设置tableGrob背景颜色

时间:2016-09-04 01:44:52

标签: r ggplot2 gridextra

我希望设置tableGrob myTable第一列的背景颜色。我希望(row1,col1)的颜色为红色,(row2,col1)为蓝色。我只看到灰色背景。使用gridExtra_0.9.1,data.table_1.9.4,ggplot2_1.0.1

library(ggplot2)
library(data.table)
library(gridExtra)  
GetCellNumber <- function(table,irow,jcol) {
  rows = NROW(table)
  cellnumber <- (jcol)*(rows+1) + irow +1
  cellnumber
}

ColorTable <- function(table, sdata,colors) {
  for(irow in 1:NROW(sdata)) {
    irowColor <- colors[irow]
    jcol <- 1
    cell <- GetCellNumber(sdata,irow,jcol)
    table$lg$lgf[[cell]]$gp$fill <- irowColor
  }
  table
}

testTable <- function(dt) {
  myTable <- tableGrob(dt, rows = NULL,
             par.coretext = gpar(fontsize=10),
             gpar.coltext = gpar(cex=0.7, fontface = "bold"), 
             gpar.coretext = gpar(cex=0.7) ,
             gpar.colfill = gpar(fill="grey90", col="gray30", lwd=0.2), 
             gpar.corefill = gpar(fill="grey90", col="gray30", lwd=0.2), 
             show.rownames = FALSE)
  myTable <-  ColorTable(myTable, dt, c("red", "blue"))
  myTable
}

dt <- data.frame(customer=c("yahoo", "cnn"), metricname=c("cpu","cpu"))
summary.table <- testTable(dt)
bottom.view <- arrangeGrob(summary.table, widths = c(1), ncol=1, 
               main= textGrob("test", 
               gp = gpar(fontsize=10, fontface="italic")))
print(bottom.view)

2 个答案:

答案 0 :(得分:1)

我无法使您的代码正常工作,但这适用于您创建的data.frame。

find_cell <- function(table, row, col, name="core-fg"){
l <- table$layout
which(l$t==row & l$l==col & l$name==name)
}

grid.newpage()
dt <- data.frame(customer=c("yahoo", "cnn"), metricname=c("cpu","cpu"))
g <- tableGrob(dt, rows = NULL)
yahoo <- find_cell(g, 2, 1, "core-bg")
cnn <- find_cell(g, 3, 1, "core-bg")
g$grobs[yahoo][[1]][["gp"]] <- gpar(fill="blue")
g$grobs[cnn][[1]][["gp"]] <- gpar(fill="red")
grid.draw(g)

Table

答案 1 :(得分:0)

对于gridExtra_0.9.1,需要覆盖drawDetails.table,以使其正常工作。有关详细信息,请参阅以下说明 https://stackoverflow.com/a/23820048/172935