0

I have a table (top.table) I would like to display in a ggplot, but am having issues reformatting the table. I need to format it such that all NA elements are blank, and only fill with specified colors if there is a number contained within the element. Basically, fill the colors like in the code below except the NA elements should be filled default (white), and the NA text should be removed. If the removing of the NA is not possible in the way I described, changing the text color/fill would also work for me (i.e. change text color/fill of numbers, but not NA).

top.table <- structure(c(7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 57.5, 45.5, 
NA, NA, NA, 128.5, 78.5, 71.5, 49, NA, NA, NA, 1043, NA, NA, 
710, 838, 1481, 737, NA, NA, 1096, 5923, 3697, NA, 1726, NA, 
NA, 3545, NA, NA, 1733, 2333, NA, 3807, 1795, NA, 2761, NA, 2887, 
NA, NA, 2211, 2544), .Dim = c(11L, 5L), .Dimnames = list(NULL, 
    c("Sample Number", "Static", "D10 FB", "D12 FB", "D14 FB"
    )))

colors <- structure(list(newcolor = c("dodgerblue2", "#E31A1C", "#FDBF6F", 
"palegreen2", "skyblue2", "green4", "#6A3D9A", "#FF7F00", "gold1", 
"#CAB2D6", "#FB9A99")), row.names = c(NA, -11L), class = c("tbl_df", 
"tbl", "data.frame"))

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = colors, col = NA))
)

g <- tableGrob(top.table, theme = tt1)
grid.draw(g)    
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
user13589693
  • 369
  • 1
  • 8

2 Answers2

0

This may seem like a very obvious solution, but why not just replace the NA with empty strings when you plot the table?

g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.newpage()
grid.draw(g) 

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0

With help from @AllanCameron, the solution I came up with was to use repeat the colors to the number of columns in top.table and use replace() to convert all NA elements to "white" before calling tableGrob()

#make repeated columns of colors
table.colors <- matrix(rep(colors, each = ncol(top.table)), 
                       ncol = ncol(top.table), byrow = TRUE)

#index matrix to fine NAs
table.ind <- is.na(top.table)

#make replacements
table.colors <- replace(table.colors, table.ind, "white")

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = table.colors))
)

g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.draw(g)
user13589693
  • 369
  • 1
  • 8