Search code examples
rgt

Matching colours with column values in gt


I have a simple piece of code that tries to publish a table which colours columns according to the colour listed in the contents using the package gt.

df <- data.frame(name = c("john", "paul", "ringo"),
                 fav_colour = c("red", "blue", "green"))

df %>% gt() %>% data_color(columns = fav_colour, colors = fav_colour)

However, as you can see the colours plotted do not match up correctly.

I appreciate that this is a known issue in gt, as described on package github and that no fix has been implemented to the package yet.

I was wondering if either someone has discovered a workaround to this in gt or can recommend a different table publishing package that has equivalent functionality.


Solution

  • Try this ...

    library(tidyverse)
    library(gt)
    
    df <- data.frame(name = c("john", "paul", "ringo"),
                     fav_colour = c("red", "blue", "green"))
    
    df %>% 
      mutate(fav_colour = fct_inorder(fav_colour)) |> 
      gt() %>% 
      data_color(columns = fav_colour, colors = as.character(fav_colour))
    

    enter image description here

    Created on 2022-04-28 by the reprex package (v2.0.1)