0

I have a question regarding tableGrob/grid.table from the gridExtra package. Is there a way to customize different colors for each column? So far and in this stackoverflow link, I have only found how to customize for different rows or cell specific.

Much obliged for any suggestion if possible!

2 Answers2

0

you can pass a vector of colours (fills) for each individual cell,

fills <- rep(blues9, each=nrow(iris[1:4, 1:3]))
tt <- ttheme_default(core=list(bg_params=list(fill=fills)))

grid.table(iris[1:4, 1:3], theme=tt)
0

grid.table column color/fill: This example is gradient fill for a single column.

library(grid)
library(gridExtra)
library(scales)
library(dplyr)

# build a vector color/fill choice for the first two columns
blkz <- rep(c("NA", "NA"), times = c(4,4))  #NA is for transparent

# generate continuous color scales based off a vector of colors from https://themockup.blog/posts/2020-05-16-gt-a-grammer-of-tables/
red_color_generator <- scales::col_numeric(c("red", "white"), domain = NULL)

redz2 <-red_color_generator(seq(10, 60, by = 10))[1:4] #%>% scales::show_col()

# cmobine the two vectors
blkz_redz <- c(blkz, redz2)

tt <- ttheme_default(core=list(bg_params=list(fill= blkz_redz, col = "gray56")))
dev.off()
grid.table(iris[1:4, 1:3], theme=tt)

enter image description here

#~~~~~~ To make the color fill conditioned on the value in the variable. Follow this steps.

#conditional color mapper function
clrize <- 
  function(df, x) {
                   df %>% 
                       mutate(cc =
                              ifelse(x == 1.3, "#FFB299",
                              ifelse(x == 1.4, "#FF8969",
                              ifelse(x == 1.5, "#FF5B3A", 
                              "#FF0000"))))
                }


#map this to the column build a vector
dt <- iris[1:4,1:3] %>% as.data.frame()  

# apply color based on the value on petal.length variable        
clrize(dt, dt$Petal.Length)  -> redz3

# cmobine the two vectors
blkz_redz <- c(blkz, redz3$cc) # cc is var added inside the function

tt <- ttheme_default(core=list(bg_params=list(fill= blkz_redz, col = "gray56")))
dev.off()
grid.table(iris[1:4, 1:3], theme=tt)

enter image description here

Antex
  • 1,364
  • 4
  • 18
  • 35