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

ng2-charts多系列环形图实现:内外环数据与标签数量不同问题问询

双系列不等长环形图实现方案

ng2-charts底层依赖Chart.js,默认全局labels会应用到所有数据集,要实现不同数据集用独立标签、内外环数据长度不一致的效果,需要单独配置每个数据集的labels属性,同时自定义tooltip、图例的取值逻辑,具体实现如下:

第一步:调整组件内配置

import { ChartConfiguration } from 'chart.js';

// 双层环形图基础配置
public doughnutChartOptions: ChartConfiguration<'doughnut'>['options'] = {
  responsive: true,
  plugins: {
    legend: {
      // 自定义图例,可按需选择展示内外环标签
      labels: {
        generateLabels: (chart) => {
          const datasets = chart.data.datasets;
          const labels = [];
          // 添加外环(父级)标签
          datasets[0].labels.forEach((label, idx) => {
            labels.push({
              text: label,
              fillStyle: datasets[0].backgroundColor[idx],
              datasetIndex: 0,
              index: idx
            })
          });
          // 需要展示内环标签时取消注释下方代码
          // datasets[1].labels.forEach((label, idx) => {
          //   labels.push({
          //     text: label,
          //     fillStyle: datasets[1].backgroundColor[idx],
          //     datasetIndex: 1,
          //     index: idx
          //   })
          // });
          return labels;
        }
      }
    },
    tooltip: {
      // 自定义tooltip,读取当前数据集对应的独立标签
      callbacks: {
        label: (context) => {
          const dataset = context.dataset;
          return `${dataset.labels[context.dataIndex]}: ${context.parsed}`;
        }
      }
    }
  },
  // 控制环形整体镂空比例
  cutout: '60%'
};

// 数据集配置
public doughnutChartDatasets: ChartConfiguration<'doughnut'>['data']['datasets'] = [
  {
    labels: ['parent1', 'parent2', 'parent3'],
    // 短数据集补0对齐长数据集长度,对应位置设透明避免多余色块
    data: [34, 50, 26, 0, 0, 0],
    backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', 'transparent', 'transparent', 'transparent'],
    borderColor: ['#FF6384', '#36A2EB', '#FFCE56', 'transparent', 'transparent', 'transparent'],
    borderWidth: 1,
    // weight控制当前环的宽度占比,数值越大环越宽
    weight: 0.6
  },
  {
    labels: ['child1_1', 'child1_2', 'child2_1', 'child2_2', 'child3_1', 'child3_2'],
    data: [14, 20, 30, 20, 10, 16],
    backgroundColor: ['#FF8A9E', '#FFB1C1', '#74B9FF', '#A4CBFF', '#FFE393', '#FFF0C2'],
    borderWidth: 1,
    weight: 0.4
  }
];

// 全局labels留空,使用各数据集独立标签
public doughnutChartLabels: string[] = [];

第二步:模板调用

<base-chart
  type="doughnut"
  [data]="{ datasets: doughnutChartDatasets, labels: doughnutChartLabels }"
  [options]="doughnutChartOptions"
>
</base-chart>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:06:03