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

ApexCharts如何按分类组为柱状图设置不同颜色?

ApexCharts分组标签柱状图按分类组设置不同颜色的解决方案

你遇到的问题核心在于:整个图表只有单个series,所以直接用colors数组只会应用第一个颜色;而之前的fill颜色函数依赖seriesIndex,但单个series的seriesIndex始终为0,导致分组判断失效。

下面提供两种可行的解决方法:

方法一:在数据点中直接指定颜色

直接在每个data对象里通过fill.color属性指定对应颜色,配合年份判断实现分组配色:

var options = {
  series: [{
    name: "sales",
    data: [
      { x: '2019/01/01', y: 400, fill: { color: '#FF0000' } },
      { x: '2019/04/01', y: 430, fill: { color: '#FF0000' } },
      { x: '2019/07/01', y: 448, fill: { color: '#FF0000' } },
      { x: '2019/10/01', y: 470, fill: { color: '#FF0000' } },
      { x: '2020/01/01', y: 540, fill: { color: '#00FFFF' } },
      { x: '2020/04/01', y: 580, fill: { color: '#00FFFF' } },
      { x: '2020/07/01', y: 690, fill: { color: '#00FFFF' } },
      { x: '2020/10/01', y: 690, fill: { color: '#00FFFF' } }
    ]
  }],
  chart: { type: 'bar', height: 380 },
  xaxis: {
    type: 'category',
    labels: { formatter: val => "Q" + dayjs(val).quarter() },
    group: {
      style: { fontSize: '10px', fontWeight: 700 },
      groups: [{ title: '2019', cols: 4 }, { title: '2020', cols: 4 }]
    }
  },
  title: { text: 'Grouped Labels on the X-axis' },
  tooltip: {
    x: { formatter: val => "Q" + dayjs(val).quarter() + " " + dayjs(val).format("YYYY") }
  }
};

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

方法二:使用动态颜色函数(更灵活)

通过fill.colors的函数,根据每个数据点的x值解析年份,动态返回对应颜色,不需要手动给每个数据点加颜色:

var options = {
  series: [{
    name: "sales",
    data: [
      { x: '2019/01/01', y: 400 },
      { x: '2019/04/01', y: 430 },
      { x: '2019/07/01', y: 448 },
      { x: '2019/10/01', y: 470 },
      { x: '2020/01/01', y: 540 },
      { x: '2020/04/01', y: 580 },
      { x: '2020/07/01', y: 690 },
      { x: '2020/10/01', y: 690 }
    ]
  }],
  chart: { type: 'bar', height: 380 },
  xaxis: {
    type: 'category',
    labels: { formatter: val => "Q" + dayjs(val).quarter() },
    group: {
      style: { fontSize: '10px', fontWeight: 700 },
      groups: [{ title: '2019', cols: 4 }, { title: '2020', cols: 4 }]
    }
  },
  title: { text: 'Grouped Labels on the X-axis' },
  tooltip: {
    x: { formatter: val => "Q" + dayjs(val).quarter() + " " + dayjs(val).format("YYYY") }
  },
  // 核心配置:动态颜色判断
  fill: {
    colors: [function({ value }) {
      // 解析当前数据点的年份
      const year = dayjs(value.x).format('YYYY');
      // 根据年份返回对应颜色
      return year === '2019' ? '#FF0000' : '#00FFFF';
    }]
  }
};

var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

关键说明

  • 方法一适合数据固定、分组明确的场景,配置直观;
  • 方法二更适合动态数据场景,不需要修改原始数据结构,通过函数自动匹配颜色;
  • 两种方法都依赖dayjs解析日期,确保你的项目中已引入dayjs库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:05:11