0

I wish to set background color of first column of my tableGrob myTable. I would like the color of (row1, col1) to be red and (row2, col1) to be blue. I am only seeing gray background. using 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)
Susan
  • 403
  • 6
  • 14
  • try with a recent version of gridExtra (the syntax has changed, but the wiki has many examples to help) – baptiste Sep 04 '16 at 05:33

2 Answers2

1

I could not get your code to work, but this works for the data.frame you created.

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

JakeC
  • 292
  • 3
  • 11
  • Thanks Jake. What version of gridExtra, ggplot2 and gridExtra are using. I have to for the moment keep it the same as what I mentioned above for now – Susan Sep 04 '16 at 06:14
0

For gridExtra_0.9.1, looks like drawDetails.table needs to be overridden for this to work. Please refer to the following explanation for details https://stackoverflow.com/a/23820048/172935

Community
  • 1
  • 1
Susan
  • 403
  • 6
  • 14