你能在 r 中的 gt table 中给相邻的单元格着色吗?

Can you color an adjacent cell in gt table in r?

a1 和 b1 根据它们的值进行着色。我希望 a2 与 a1 颜色相同,b2 与 b1 颜色相同。这可能吗?

library(dplyr)
library(gt)
library(viridis)

set.seed(123)
df <- data.frame(exp = (LETTERS[1:5]),
           a1 = sample(x = 1:20, size  = 5),
           a2 = sample(x = 1:10, size  = 5),
           b1 = sample(x = 1:20, size  = 5),
           b2 = sample(x = 1:10, size  = 5))

df %>% 
  gt() %>% 
  data_color(
        columns = c(a1,b1),
        colors = scales::col_numeric(
          palette = viridis(20, direction = 1, option ="D"), #color from viridis package
          domain = NULL)
      )

非常感谢!!

我的第一直觉是在 gt 对象中获取 a1b1 的颜色:

  • 但是在那里找不到它们,所以

接下来我创建了一个颜色矢量,如

#install.packages("colourvalues")
library(colourvalues)
colors <- color_values(df$a1)

并希望将其应用于 data_color 中的 colors 参数,用于列 a2

在同一站点上,@jthomasmock 在 gt.

之前提供了自己的 html 解决方案
  • 但这会根据深色背景上的文本字体引发问题,

我可以在@stefan 的帮助下解决:

#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()