ixodid
ixodid

Reputation: 2380

How shade cells in gt table based on value of characters in cells?

Here is a simple gt table. How do I shade FSRA = red, DGCM = blue and CDIC = yellow?

library(gt)
library(tidyverse)

ins_levels <- c("CDIC", "DGCM", "FSRA")

df <- tibble(
  comp = letters[1:5],
  ins = factor(c("FSRA", "CDIC", "CDIC", "DGCM", "DGCM"), ins_levels)
)

df |> gt() |> 
  data_color(
    columns = ins,
    colors = scales::col_factor(
      palette = c("red", "yellow", "blue"),
      domain = c("FSRA", "CDIC", "DGCM")
    ),
    apply_to = "fill",
    autocolor_text = FALSE
  )

Upvotes: 2

Views: 63

Answers (1)

akrun
akrun

Reputation: 886948

The palette order should match the levels of the column i.e. ins_levels

ins_levels <- c("CDIC", "DGCM", "FSRA")

df <- tibble(
  comp = letters[1:5],
  ins = factor(c("FSRA", "CDIC", "CDIC", "DGCM", "DGCM"), levels = ins_levels)
)
levels(df$ins)
#[1] "CDIC" "DGCM" "FSRA"

df |> gt() |> 
  data_color(
    columns = ins,
    colors = scales::col_factor(
      palette = c("yellow", "blue", "red"),
      domain = ins_levels
    ),
    apply_to = "fill",
    autocolor_text = FALSE
  )

-output

enter image description here

Upvotes: 2

Related Questions