This question is somehow related but not depending to this Can you color an adjacent cell in gt table in r?:
I am explicitly looking for the modification of the <span style=\...</span> part of my code!
I have this example dataset with colors of the background of mpg column depending on the values applied with html.
library(dplyr)
library(purrr)
library(gt)
library(viridis)
head(mtcars[,1:2]) %>%
mutate(
color = scales::col_numeric(
palette = viridis(20, direction = 1, option ="D"), #color from viridis package
domain = NULL)(mpg),
mpg = glue::glue('<span style=\"display: inline-block; direction: ltr; border-radius: 5px; padding-right: 2px; background-color: {color}; width: 100%\"> {mpg} </span>'),
mpg = map(mpg, ~gt::html(as.character(.x)))
) %>%
select(-color) %>%
gt()
which gives:
I would like to have the text in mpg column in white color conditional to dark background coded in the inline html part of my code e.g. before transforming to an gt object.
While this works: This is not what I am looking for!
library(dplyr)
library(gt)
library(viridis)
head(mtcars[,1:2]) %>%
gt() %>%
data_color(
columns = c(mpg),
colors = scales::col_numeric(
palette = viridis(20, direction = 1, option ="D"), #color from viridis package
domain = NULL)
)
gives:
I have tried so far: adding color:white to inline html
head(mtcars[,1:2]) %>%
mutate(
color = scales::col_numeric(
palette = viridis(20, direction = 1, option ="D"), #color from viridis package
domain = NULL)(mpg),
mpg = glue::glue('<span style=\"display: inline-block; direction: ltr; color:white; border-radius: 5px; padding-right: 2px; background-color: {color}; width: 100%\"> {mpg} </span>'),
mpg = map(mpg, ~gt::html(as.character(.x)))
) %>%
select(-color) %>%
gt()
which gives:
>Solution :
One option would be prismatic::best_contrast. By default it will not use pure white so we have to set the colors:
prismatic::best_contrast("red", c("white", "black"))
#> [1] "black"
prismatic::best_contrast("purple", c("white", "black"))
#> [1] "white"
This could be added easily to your glue string to set font color based on the background color:
head(mtcars[, 1:2]) %>%
mutate(
color = scales::col_numeric(
palette = viridis(20, direction = 1, option = "D"), # color from viridis package
domain = NULL
)(mpg),
mpg = glue::glue(
'<span style=\"display: inline-block; direction: ltr; border-radius: 5px; padding-right: 2px;',
'color: {prismatic::best_contrast(color, c("white", "black"))}; background-color: {color}; width: 100%\"> {mpg} </span>'
),
mpg = map(mpg, ~ gt::html(as.character(.x)))
) %>%
select(-color) %>%
gt()



