R gt: color a column by another column's value

Viewed 338

I would like to create a gt table where I display numeric values from two columns together in a single cell, but color the cells based on just one of the column's values.

For example using the ToothGrowth example data I'd like to put the len and dose columns together in a single cell but color the cell backgrounds by the value of dose.

I tried to manually create a vector of colors to color the len_dose column but this does not work because it seems like it is reapplying the color vector to each different level of len_dose, not dose. I guess you could manually format the cells with tab_style() but that seems inefficient and does not give you the nice feature where the text color changes to maximize contrast with background. I don't know an efficient way to do this.

What I tried:

library(gt)
library(dplyr)
library(scales)
library(glue)

# Manually map dose to color
dose_colors <- col_numeric(palette = 'Reds', domain = range(ToothGrowth$dose))(ToothGrowth$dose)

ToothGrowth %>%
  mutate(len_dose = glue('{len}: ({dose})')) %>%
  gt(rowname_col = 'supp') %>%
  cols_hide(c(len, dose)) %>%
  data_color(len_dose, colors = dose_colors)  

Output (not good because not colored by dose):

enter image description here

1 Answers

Not sure if you found a solution to this yet but here is what I did:

  • If you use tab_style() you don't need to try and create the vector of colors and can instead set the background color you want based on the dose column. If you want to color values differently based on dose, in addition to what I've colored here, then create another tab_style() for the desired value.

    library(gt)
     library(dplyr)
     library(scales)
     library(glue)
    
     ToothGrowth %>%
       mutate(len_dose = glue('{len}: ({dose})')) %>%
       gt(rowname_col = 'supp') %>%
       tab_style(
         style = cell_fill(color = "palegreen"),
         location = cells_body(
           columns = len_dose,
           rows = dose >= 1.0
         )
       ) %>%
       cols_hide(c(len, dose))
    

enter image description here

Related