I have a data frame a
with three columns, and another dataframe of exactly the same size p
with values that I want to use to colour in table a
.:
a <- data.frame(name=c("cat", "dog"), age=c(1,2), weight=c(4,2))
p <- data.frame(name=c(1, 0), age=c(1,1), weight=c(1,0))
# I bind the values together
a <- cbind(a, p %>% set_names(paste0("_",names(p))))
# using gt's target_columns, I can can map colours across
a %>% gt() %>%
data_color(
columns = names(a)[grepl("_",names(a))],
target_columns = names(a)[!grepl("_",names(a))],
method = "numeric",
palette = c('red', 'green')
)
I'm expecting all the 1s to be green, but I get this:
Looks like the domain=
of the values for the color palette is taken from the range of the columns=
. And as the range of _age
is [1, 1]
you end up with a mix of green and red.
At least for your example data or in the case where all columns have the same range or domain you could fix that by setting the domain=
explicitly:
library(gt)
a |>
gt() |>
data_color(
columns = names(a)[grepl("_", names(a))],
target_columns = names(a)[!grepl("_", names(a))],
method = "numeric",
palette = c("red", "green"),
domain = c(0, 1)
)