You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为gt表格中Percentile列的条形图设置条件颜色?

为gt表格的Percentile条形图设置条件颜色

问题需求

需要为gt表格中Percentile列的条形图按数值区间设置不同颜色:

  • 100-90区间:使用一种颜色
  • 90-80区间:使用另一种颜色
  • 80-70区间:使用第三种颜色
  • 70-60区间:使用第四种颜色
  • 60以下:使用第五种颜色

解决方案

通过给数据添加颜色分组列,结合gt_plt_bar_pct的动态填充功能即可实现需求,具体步骤如下:

1. 预处理数据,添加颜色映射列

根据Percentile的数值区间,为每行分配对应的颜色值:

library(dplyr)
library(gt)
library(gtExtras)

# 加载数据
player_percentiles <- structure(list(Stat = structure(1:23, levels = c("Passes Completed", 
"Passes Attempted", "Pass Completion %", "Total Passing Distance", 
"Progressive Passing Distance", "Progressive Distance %", "Short Passes Completed", 
"Short Passes Attempted", "Short Pass Completion %", "Medium Passes Completed", 
"Medium Passes Attempted", "Medium Pass Completion %", "Long Passes Completed", 
"Long Passes Attempted", "Long Pass Completion %", "Assists", 
"xAG: Exp. Assisted Goals", "xA: Expected Assists", "Key Passes", 
"Passes into Final 1/3", "Passes into Penalty Area", "Crosses into Penalty Area", 
"Progressive Passes"), class = "factor"), `Per 90` = c("64.3", 
"75.9", "84.1%", "1177.9", "345.5", "29.4%", "27.5", "30.2", 
"90.8%", "26.9", "30.2", "88.6%", "8.1", "11.3", "70.8%", "0.08", 
"0.13", "0.14", "1.32", "7.31", "1.78", "0.17", "8.64"), perc_value = c(94, 
94, 65, 96, 95, 61, 86, 86, 73, 94, 96, 68, 98, 95, 80, 46, 69, 
73, 66, 95, 92, 63, 96), Percentile = c(94, 94, 65, 96, 95, 61, 
86, 86, 73, 94, 96, 68, 98, 95, 80, 46, 69, 73, 66, 95, 92, 63, 
96)), row.names = c(NA, -23L), class = c("tbl_df", "tbl", "data.frame"
))

# 添加颜色映射列
player_percentiles <- player_percentiles %>%
  mutate(bar_color = case_when(
    Percentile >= 90 ~ "#2E8B57",    # 深绿色:90-100区间
    Percentile >= 80 ~ "#90EE90",    # 浅绿色:80-90区间
    Percentile >= 70 ~ "#FFFF00",    # 黄色:70-80区间
    Percentile >= 60 ~ "#FFA500",    # 橙色:60-70区间
    TRUE ~ "#FF0000"                 # 红色:60以下区间
  ))

2. 修改gt表格代码,应用动态颜色

将gt_plt_bar_pct的fill参数指定为新增的bar_color列,即可实现按区间变色的条形图:

player_percentiles %>%
  gt() %>%
  gt_plt_bar_pct(Percentile, labels = F, fill = bar_color) %>%  # 引用颜色列实现动态填充
  cols_width(Percentile ~ px(200)) %>%
  opt_row_striping() %>%
  cols_align(align = "left", columns = Stat) %>%
  cols_align(align = "center", columns = Percentile) %>%
  opt_stylize(style = 1, color = "gray") %>%
  cols_label(perc_value = "") %>%
  tab_style(
    style = cell_text(color = "darkred"),
    locations = cells_body(columns = perc_value)
  )

自定义说明

  • 可根据偏好修改case_when中的十六进制颜色代码
  • 若需调整区间划分,直接修改case_when中的数值条件即可
  • gt_plt_bar_pct支持将列名作为fill参数,实现每行条形图的颜色自定义

内容的提问来源于stack exchange,提问作者Lucas Varela

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:53:11