我的第一直觉是抓住颜色a1
and b1
in the gt
object:
接下来我创建了一个颜色向量,例如
#install.packages("colourvalues")
library(colourvalues)
colors <- color_values(df$a1)
并想将其应用到colors
参数输入data_color
对于列a2
- 但根据这个问题这是不可能的https://github.com/rstudio/gt/issues/633 https://github.com/rstudio/gt/issues/633.
在同一个网站上,@jthomasmock 之前提供了一个带有自己的 html 的解决方案gt
.
我可以在@stefan的帮助下解决:从调色板设置背景后,如何使用 INLINE HTML 自动使深色背景上的文本变为白色 https://stackoverflow.com/questions/70728687/how-to-use-inline-html-to-make-text-white-on-dark-background-automatically-after/70728727#70728727
#install.packages("prismatic")
library(dplyr)
library(purrr)
library(gt)
library(viridis)
library(prismatic)
df %>%
mutate(
color = scales::col_numeric(
palette = viridis(20, direction = 1, option ="D"), #color from viridis package
domain = NULL)(a1),
a1 = 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%\"> {a1} </span>'
),
a1 = map(a1, ~gt::html(as.character(.x))),
a2 = 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%\"> {a2} </span>'
),
a2 = map(a2, ~gt::html(as.character(.x))),
) %>%
mutate(
color = scales::col_numeric(
palette = viridis(20, direction = 1, option ="D"), #color from viridis package
domain = NULL)(b1),
b1 = 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%\"> {b1} </span>'
),
b1 = map(b1, ~gt::html(as.character(.x))),
b2 = 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%\"> {b2} </span>'
),
b2 = map(b2, ~gt::html(as.character(.x))),
) %>%
select(-color) %>%
gt()