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

如何在gt_plt_bar()中设置多种颜色自定义条形填充?

报错原因

gt_plt_bar()的color参数原生设计不支持直接传入与行数等长的颜色向量,仅支持单个固定颜色或调色板生成函数,你传入16位长度的颜色向量时触发了函数内部逻辑错误。

可行解决方案

你可以通过将颜色向量封装为匿名函数的方式适配参数要求,修改后的运行代码如下:

remotes::install_github("jthomasmock/gtExtras")

library(gt)
library(gtExtras)

ex <- data.frame(
  a = c(9.1, 11.8, 0.9, 5.6, 2.5, 1.7, 1.4, 2.4, 5.1, 8.2, 6.6, 4.4, 2.7, 2.3,
        2.2, 6.7)
)

a_colors <- c("#97233f", "#241773", "#0b162a", "#fb4f14", "#002244",
              "#002244", "#203731", "#000000", "#002244", "#008e97",
              "#4f2683", "#203731", "#004953", "#000000", "#002244",
              "#aa0000")

ex %>%
  gt() %>%
  gt_plt_bar(
    column = a, 
    keep_column = TRUE, 
    # 用匿名函数返回对应颜色向量适配参数要求
    color = function(x) a_colors
  )

如果上述方法在你安装的版本中不生效,可以使用更通用的text_transform自定义条形渲染逻辑,无需依赖gtExtras的封装:

library(gt)
library(glue)

ex <- data.frame(
  a = c(9.1, 11.8, 0.9, 5.6, 2.5, 1.7, 1.4, 2.4, 5.1, 8.2, 6.6, 4.4, 2.7, 2.3,
        2.2, 6.7)
)

a_colors <- c("#97233f", "#241773", "#0b162a", "#fb4f14", "#002244",
              "#002244", "#203731", "#000000", "#002244", "#008e97",
              "#4f2683", "#203731", "#004953", "#000000", "#002244",
              "#aa0000")

ex %>%
  gt() %>%
  text_transform(
    locations = cells_body(columns = a),
    fn = function(x) {
      x_num <- as.numeric(x)
      max_val <- max(x_num)
      lapply(seq_along(x_num), function(i) {
        width_pct <- round(x_num[i]/max_val * 100, 1)
        glue(
          '<div style="display: flex; align-items: center; justify-content: flex-start;">
            <span style="width: 3em; display: inline-block;">{x_num[i]}</span>
            <div style="background-color: {a_colors[i]}; width: {width_pct}%; height: 1em; border-radius: 3px; margin-left: 4px;"></div>
          </div>'
        )
      })
    }
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:09:01