Search code examples
rcolorsgt

gt() from gt colors cells w/ same content differently?


I am trying to make my table more intuitive by coloring the cells based on their content, hence gt(). However, cells with identical content are being colored differently, not even in the same color group. If any of you have suggestions on how to fix this, I would appreciate that a lot.

Picture for reference enter image description here

The desired outcome should have green for TRUE, black for FALSE, blue for "Upcoming" and red for "Missed"

I only used data_color(gt(df), col = c(5, 11)). I tried limiting the number of colors through palette = c("red", "blue", "green", "black") but it did not work either.


Solution

  • Using data_color you can specify a color-mapping function that will use col_*() functions from the scales package.

    library(gt)
    
    df <- data.frame(
      on_time_W2 = c("Missed visit", "Missed visit", "TRUE", "TRUE", "TRUE"),
      on_time_W4 = "Missed visit",
      on_time_W6 = c("FALSE", "Missed visit", "FALSE", "Missed visit", "Missed visit"),
      on_time_W26 = c("TRUE", "Upcoming visit", "TRUE", "Upcoming visit", "Upcoming visit")
    )
    
    df |>
      gt() |>
      data_color(
        fn = scales::col_factor(
          palette = c("green", "black", "red", "blue"),
          levels = c("TRUE", "FALSE", "Missed visit", "Upcoming visit")
        ),
        apply_to = "fill"
      )
    

    Table

    table with colored cells using gt and data_color