我有一个数据表,每个项目旁边都有颜色名称。我想将 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 参考中使用十六进制代码复制示例(参见下图),但无法使其工作,甚至示例代码也为我抛出了错误。
。
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)
)
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)
)