gt R Tables - Colour entire rows based on values in one column

Viewed 77

I'd like to colour an entire row based on the values in one column using the R package gt. What I'd like is shown below, where rows are red for the smallest values of mpg, and blue for the highest values.

table of mtcars with rows coloured by the values in the mpg column

Using the code below:

mtcars |> 
  head() |> 
  select(mpg, cyl, disp, drat) |> 
  gt() |> 
  data_color(
    columns = mpg,
    colors = scales::col_numeric(
      palette = c("red", "orange", "green", "blue"),
    domain = c(18, 23))
  )

Gives the right behaviour only for the mpg column itself.

gt table with only one column coloured

1 Answers

One option would be to create breaks, then use that for the rows argument in tab_style rather than using data_color (which doesn't have a rows argument). Here, I set the breaks using cut, but you could use something like ntile to break up into groups (commented out below).

library(tidyverse)
library(gt)

mtcars |>
  head() |>
  select(mpg, cyl, disp, drat) |>
  #mutate(breaks = ntile(mpg, 4)) |>
  mutate(breaks = cut(mpg, breaks = c(0, 18.2, 18.8, 21.5, 30), right = T, labels = F)) |>
  gt() |>
  tab_style(
    style = cell_fill(color = "red"),
    locations = cells_body(
      rows = breaks == 1)
  ) |>
  tab_style(
    style = cell_fill(color = "orange"),
    locations = cells_body(
      rows = breaks == 2)
  ) |>
  tab_style(
    style = cell_fill(color = "green"),
    locations = cells_body(
      rows = breaks == 3)
  ) |>
  tab_style(
    style = cell_fill(color = "blue"),
    locations = cells_body(
      rows = breaks == 4)
  )

Output

enter image description here

Related