在gt表格中动态自定义边框颜色

问题描述 投票:0回答:1

我有一个 gt 表格,需要多列边框。我可以轻松更改目标行和/或列的颜色,正如您在本示例中看到的,将“无花果”的边框更改为紫色。

library(dplyr)

exibble %>%
  gt() %>%
  cols_align(align = "center",
             columns = c("char")) %>%
  tab_style(
    style = list(
      cell_borders(
        sides = c("all"),
        color = c("purple"),
        weight = px(3)
      )
    ),
    locations = list(
      cells_body(
        columns = "char",
        rows = char == "fig"
      )
    )
  )

Targeted fig color

但是,当我尝试从包含颜色的另一列一次更改多种颜色时,出现错误:

exibble %>%
  mutate(col = case_when(char == "fig" ~ "purple",
                         char == "banana" ~ "yellow",
                         TRUE ~ "white")) %>%
  gt() %>%
  cols_align(align = "center",
             columns = c("char")) %>%
  tab_style(
    style = list(
      cell_borders(
        sides = c("all"),
        color = from_column(col),
        weight = px(3)
      )
    ),
    locations = list(
      cells_body(
        columns = "char",
        rows = !is.na(col)
      )
    )
  )

Error in `cell_borders()`:
! `color` must have a length one, not 3.

如何使整个列反映预期的边框颜色(白色、紫色或黄色),而不必一一定位这些单元格值?

r gt
1个回答
0
投票

使用

cell_fill
功能可设置多种单元格颜色。

exibble %>%
  mutate(col = case_when(char == "fig" ~ "purple",
                         char == "banana" ~ "yellow",
                         TRUE ~ "white")) %>%
  gt() %>%
  cols_align(align = "center",
             columns = c("char")) %>%
  tab_style(
    style = cell_fill(color = from_column(column = "col")),
    locations = cells_body(columns = col)
  )
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.