Search code examples
rcolorsgt

How can I modify the color of the group name rows in a gt table?


I'd like to shade the groupname labels in a gt table so that it corresponds with a nearby plot, in lieu of a legend on the plot itself. Ideally, this color would be filling in the row and not changing the color of the text.

This minimal example doesn't produce any errors, but it also doesn't do what I want it to.

library(dplyr)
library(gt)

mtcars |> 
  arrange(carb) |> 
  gt(groupname_col = "carb", rownames_to_stub = T) |> 
  tab_stub_indent(everything(), 5) |> 
  data_color(columns = "carb", palette = "Blues")

Solution

  • tab_style() can be used to change the style of cells. It takes as argument a style and a location that specifies where the style should be applied. To fill the background of the cells with a colour, you can use cell_fill(). cells_row_groups() can be used to select the row group header rows.

    Since each row group header should have a different colour, I apply the styling in a loop. I'm taking the colours from the palette "Blues" from RColorBrewer. You will have to figure out the appropriate colours somehow.

    tab <- mtcars |> 
      arrange(carb) |> 
      gt(groupname_col = "carb", rownames_to_stub = TRUE) |> 
      tab_stub_indent(everything(), 5)
    
    values <- unique(mtcars$carb)
    colours <- RColorBrewer::brewer.pal(length(values), "Blues")
    
    for (i in seq_along(values)) {
      tab <- tab |>
        tab_style(cell_fill(colours[i]), cells_row_groups(i))
    }
    
    tab
    

    I applied the code to a variant of mtcars, where I only kept one row for each value of carb. This is what I got:

    enter image description here