rdataframecolorsgt

gt color based on color strings from a column


I have been looking for the simplest, most direct way of colorizing a column based on the color string value (i.e. red or #FF0000) within a {gt} table.

library(gt)

df <- data.frame(
  name = c("john", "jane", "jack"),
  color_var = c("red", "blue", "green"))

# We want <name> to be filled with the colors in <color_var>
df |> 
  gt() |>
  tab_style(
    style = cell_fill(color = from_column("color_var")),
    locations = cells_body(column=name)
  )

This works though not elegant in my opinion, because tab_style() can be used for many other duties. I'm sure I can use gt::data_color() function which seems fit for the task, but I can't find how ! Here's some code I'd like to see :

df |>
  gt() |> 
  data_color(columns = name,
             # fn = scales::col_factor(color_var) ... ? 
             # palette = color_var ... ?
             )

Thanks !


Solution

  • Pass the color column to the columns argument, and use the target_columns argument with fn = identity to apply to the targeted columns.

    library(gt)
            
    df |> 
      gt() |> 
      data_color(columns = color_var,
                 target_columns = name,
                 fn = identity)
    

    enter image description here