使用 R 中的 gt 包按命名颜色为单元格着色

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

我有一个数据表,每个项目旁边都有颜色名称。我想将 colA 或 colC 的单元格颜色更改为指定的颜色。我首选的表输出是使用 gt 包。例如:


library(gt)
library(dplyr)

df<- tribble(
  ~colA, ~colB, ~colC,
  "apple",   1, "green",
  "banana",   2, "yellow",
  "cherry",   3, "red"
)

gt(df) |>
  tab_style(
    style = cell_text(font = system_fonts(name = "monospace-code")),
    locations = cells_body()
  ) |>
  cols_width(everything() ~ px(100)) |>
  tab_options(table_body.hlines.style = "all") |>
  cols_align("center") |>
  tab_style(
    style = list(
      cell_fill(color = "gray95"),
      cell_borders(sides = c("l", "r"), color = "gray50", weight = px(3))
    ),
    locations = cells_body(columns = colB)
   )

如何使用表格中的颜色信息为单元格着色。我尝试在 gt 参考中使用十六进制代码复制示例(参见下图),但无法使其工作,甚至示例代码也为我抛出了错误。

gt reference example

r gt
2个回答
1
投票
您可以将

from_column

 辅助函数与 cell_fill
 一起使用,它允许

从表中的指定列获取参数值。

因此,使用

from_column

 您可以将颜色从 
colC
 列传递到 
color=
cell_fill
 参数。

library(gt) df |> gt() |> tab_style( style = cell_text(font = system_fonts(name = "monospace-code")), locations = cells_body() ) |> cols_width(everything() ~ px(100)) |> tab_options(table_body.hlines.style = "all") |> cols_align("center") |> tab_style( style = list( cell_fill(color = from_column(column = "colC")), cell_borders(sides = c("l", "r"), color = "gray50", weight = px(3)) ), locations = cells_body(columns = colB) )


0
投票
这是另一种选择(不是很有效),使用十六进制代码手动更改行。

gt(df) |> cols_width(everything() ~ px(100)) |> tab_options(table_body.hlines.style = "all") |> cols_align("center") |> # This is the second column first row: color green tab_style( style = list( cell_fill(color = "#3CB44B"), cell_borders(sides = c("l", "r"), color = "gray95", weight = px(3)) ), locations = cells_body(columns = colB, rows = 1) ) |> # This is the second column second row: color yellor tab_style( style = list( cell_fill(color = "#FFE119"), cell_borders(sides = c("l", "r"), color = "gray95", weight = px(3)) ), locations = cells_body(columns = colB, rows = 2) ) |> # This is the second column third row: color red tab_style( style = list( cell_fill(color = "#E6194B"), cell_borders(sides = c("l", "r"), color = "gray95", weight = px(3)) ), locations = cells_body(columns = colB, rows = 3) )

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