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

如何在react-chartjs-2环形图标签中添加数据(如Red(12))

解决react-chartjs-2环形图标签显示带数据的问题

要让环形图的图例标签显示成Red(12)这种带数据的格式,你需要自定义图例标签的生成逻辑,通过修改图表配置里的plugins.legend.labels.generateLabels函数来实现。

修改后的完整代码示例

import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
} from 'chart.js';

ChartJS.register(ArcElement, Tooltip, Legend);

export const App = () => {
  const data = {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [
      {
        label: '# of Votes',
        data: [12, 19, 3],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
        ],
        borderWidth: 1,
      },
    ],
  };

  const options = {
    plugins: {
      legend: {
        labels: {
          // 自定义图例标签生成逻辑
          generateLabels: (chart) => {
            const { data } = chart;
            if (data.labels && data.datasets.length) {
              return data.labels.map((label, index) => {
                const dataset = data.datasets[0];
                return {
                  text: `${label}(${dataset.data[index]})`,
                  fillStyle: dataset.backgroundColor[index],
                  strokeStyle: dataset.borderColor[index],
                  lineWidth: dataset.borderWidth,
                };
              });
            }
            return [];
          },
        },
      },
    },
  };

  return <Doughnut data={data} options={options} />;
};

export default App;

关键说明

  • generateLabels函数会遍历每个图例标签,将标签名称和对应数据集里的数值拼接成标签名(数值)的格式
  • 同时保留了原有的背景色、边框色和边框宽度,保证图例样式和图表区块一致
  • 鼠标悬停的tooltip显示不受影响,依然会保留原有格式(如Red # of votes: 12)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:40:26