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

如何在Chart.js环形图中实现仅显示Top5数据的图例?

实现Chart.js环形图仅显示Top5数据图例

问题背景

找到过一个Chart.js折线图仅显示Top5数据图例的实现示例,但需要处理的是环形图(doughnut chart),由于不熟悉JavaScript,不知道如何修改代码实现相同的图例过滤功能。

修改方案

折线图的图例对应多个数据集(dataset),而环形图的图例对应单个数据集中的每个数据项,因此需要调整图例过滤逻辑,针对单个数据集里的每个数据值进行排序筛选:

  • 提取环形图数据集中的标签和对应数值,组成关联数组
  • 按数值从大到小排序,取前5个标签
  • 在图例过滤函数中,只保留这5个标签对应的图例项

完整代码示例

HTML部分

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

JavaScript部分

const options = {
  type: 'doughnut', // 切换为环形图类型
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Pink", "Brown", "Gray", "Cyan", "Magenta"],
    datasets: [{
      label: '# of Votes',
      data: [120, 19, 3, 5, 2, 3, 45, 28, 15, 33, 6],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 99, 132, 0.4)',
        'rgba(54, 162, 235, 0.4)',
        'rgba(255, 206, 86, 0.4)',
        'rgba(75, 192, 192, 0.4)',
        'rgba(153, 102, 255, 0.4)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          filter: (legendItem, chartData) => {
            // 生成标签与对应数值的关联数组
            const valueLabelPairs = chartData.labels.map((label, index) => [
              label,
              chartData.datasets[0].data[index]
            ]);
            
            // 按数值降序排序
            valueLabelPairs.sort((a, b) => b[1] - a[1]);
            
            // 提取前5个标签
            const top5Labels = valueLabelPairs.slice(0, 5).map(pair => pair[0]);
            
            // 仅保留Top5标签对应的图例项
            return top5Labels.includes(legendItem.text);
          }
        }
      }
    }
  }
};

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:25:39