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

Chart.js v4实现Y轴分组标签(分组含不同数量子项)

在Chart.js v4中实现Y轴分组标签(不同分组子项数量不同)

核心实现思路

Chart.js v4没有内置Y轴分组标签功能,需通过自定义插件实现,核心逻辑:

  • 定义分组与子标签的映射关系
  • 绘制前计算每个分组对应的Y轴位置区间
  • 在区间中心绘制分组标签,同时调整Y轴边距避免标签截断

完整实现代码

<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.1/chart.min.js"></script>
<script>
// 分组配置:分组名 -> 对应子标签的索引范围(闭区间)
const groupConfig = [
  { name: 'Group 1', startIndex: 0, endIndex: 0 }, // 对应标签A
  { name: 'Group 2', startIndex: 1, endIndex: 3 }, // 对应标签B、C、D
  { name: 'Group 3', startIndex: 4, endIndex: 4 }  // 对应标签E
];

new Chart('myChart', {
  type: "bar",
  data: {
    labels: ["A", "B", "C", "D", "E"],
    datasets: [
      { label: 'Min', data: [7.16, 1, 2.8, 1, 16] },
      { label: 'Max', data: [85.86, 29.55, 181.78, 70.54, 89] },
      { label: 'Average', data: [29.03, 13.17, 39.13, 40.61, 51.50] }
    ]
  },
  options: {
    indexAxis: 'y',
    layout: {
      padding: { left: 80 } // 给左侧分组标签预留空间
    },
    plugins: {
      legend: { position: 'bottom' }
    },
    scales: {
      y: {
        reverse: true,
        ticks: { padding: 20 } // 拉开子标签与分组标签的间距
      }
    },
    plugins: [
      {
        beforeDraw: (chart) => {
          const ctx = chart.ctx;
          const yAxis = chart.scales.y;
          const labelHeight = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
          
          groupConfig.forEach(group => {
            // 计算分组的中心Y坐标
            const startY = yAxis.getPixelForTick(group.startIndex);
            const endY = yAxis.getPixelForTick(group.endIndex);
            const centerY = (startY + endY) / 2;
            
            // 绘制分组标签
            ctx.save();
            ctx.font = '14px sans-serif';
            ctx.fillStyle = '#333';
            ctx.textAlign = 'right';
            ctx.textBaseline = 'middle';
            ctx.fillText(group.name, yAxis.left - 10, centerY);
            ctx.restore();
          });
        }
      }
    ]
  }
});
</script>

关键说明

  • 分组配置:groupConfig可灵活调整每个分组覆盖的子标签数量,适配不同需求
  • 边距控制:通过layout.padding.left避免分组标签被画布边缘截断
  • 居中逻辑:利用Y轴getPixelForTick方法获取子标签像素位置,计算分组中心坐标确保标签居中
  • 插件钩子:通过beforeDraw钩子在图表渲染前添加分组标签,不干扰原有图表逻辑

替代方案参考

如果需要更复杂的分组样式、交互功能,可考虑使用Chart.js第三方插件扩展,或直接使用ECharts(内置Y轴分组标签配置),但自定义插件方案已能满足你的核心需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:22:37