How to use same gradient on multiple columns in gt?

Viewed 235

I am creating this table in gt.

enter image description here

The gradient in the columns are on two different scales--notice how .1424 in Var2 is darker blue than .2206 in Var1. How might it be possible to change the palette so that both columns are on the same color scale? So in the new table the darkest blue would be the largest value in the two columns (.4199) and the darkest red would be the smallest in the two columns (.0003), all 8 other cells falling somewhere between on that spectrum?

Here is my data/code:

ex <- structure(list(Var1 = c(0.0015, 0.22058, 0.335, 0.3747612, 0.4199048
), Var2 = c(0.0002778, 0.1424279, 0.1233159, 0.1684, 0.1816663
)), class = "data.frame", row.names = c(NA, -5L))
ex %>%
  gt() %>%
  tab_header(title = md("Title")) %>%
  
  fmt_number(
    vars(`Var1`, `Var2`), decimals = 4) %>%
  
  data_color(vars(`Var1`, `Var2`),
             colors = scales::col_numeric(palette = c("red", "white", "blue"), domain = NULL)
             
  )
1 Answers

If you specify the domain (per the docs), that should solve your issue, e.g.

library(gt)
ex <- structure(list(Var1 = c(0.0015, 0.22058, 0.335, 0.3747612, 0.4199048
), Var2 = c(0.0002778, 0.1424279, 0.1233159, 0.1684, 0.1816663
)), class = "data.frame", row.names = c(NA, -5L))

ex %>%
  gt() %>%
  data_color(vars(`Var1`, `Var2`),
             scales::col_numeric(palette = c("red", "white", "blue"),
                                 domain = c(0, 0.5)))

example_1.png

If you change the color scheme you can see the gradient change more clearly, e.g.

ex %>%
  gt() %>%
  data_color(vars(`Var1`, `Var2`),
             scales::col_numeric(palette = c("red", "white"),
                                 domain = c(0, 0.5)))

example_2.png

Related