2016-09-04 21 views
0

私のtableGrob myTableの最初の列の背景色を設定したいと思います。私は、(row1、col1)の色を赤、(row2、col1)を青にしたいと思います。私は灰色の背景だけを見ている。 gridExtra_0.9.1、data.table_1.9.4、ggplot2_1.0.1設定tableGrobの背景色をR

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) 
+0

最新のgridExtraで試してください(構文は変更されましたが、wikiには多くの例があります) – baptiste

答えて

1

を使用して、私はあなたのコードを動作させることができなかったが、これは、あなたが作成したdata.frameのために動作します。 gridExtra_0.9.1については

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

+0

ありがとうございます。 gridExtra、ggplot2、gridExtraのどのバージョンが使用していますか?私は今、私が今までに述べたことと同じままにしなければならない – Susan

関連する問題