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

如何单独修改ag-charts柱状图的柱子颜色?

解决Ag-Charts单独设置每个柱子颜色且X轴标签正常显示的问题

不用拆分多个series,直接在单个bar series里通过formatter函数为每个柱子单独设置填充色,既能实现颜色自定义,又不会破坏X轴标签的正常显示。

修改后的代码示例:

import { AgChartOptions, AgCharts } from "ag-charts-community";

const options: AgChartOptions = {
  container: document.getElementById("myChart"),
  data: [
    { os: "Windows", share: 0.88 },
    { os: "macOS", share: 0.094 },
    { os: "Linux", share: 0.187 },
  ],
  title: {
    text: "Desktop Operating Systems",
  },
  series: [
    {
      type: "bar",
      xKey: "os",
      yKey: "share",
      // 通过formatter自定义每个柱子的颜色
      formatter: ({ datum }) => {
        switch(datum.os) {
          case "Windows":
            return { fill: "#2196F3" }; // 蓝色
          case "macOS":
            return { fill: "#FF9800" }; // 橙色
          case "Linux":
            return { fill: "#4CAF50" }; // 绿色
          default:
            return {}; // 默认样式
        }
      }
    },
  ],
  axes: [
    {
      type: "category",
      position: "bottom",
      label: {
        formatter: ({ value }) => {
          return value == "Windows" ? "== Windows ==" : value;
        },
      },
    },
    {
      type: "number",
      position: "left",
      label: {
        formatter: (params) => {
          return params.value * 100 + "%";
        },
      },
    },
  ],
};

const chart = AgCharts.create(options);

原理说明

  • 单个series保持了X轴category的完整性,X轴会基于xKey: "os"正常渲染所有标签
  • formatter函数接收当前柱子对应的datum(数据项),可以根据数据的属性(比如os字段)返回包含fill的样式对象,精准控制每个柱子的颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:30:05