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

如何使用react-chartjs-2在环形图图例右侧添加文本

给react-chartjs-2环形图图例右侧添加数字文本的实现方法

react-chartjs-2 基于 Chart.js 开发,要给环形图(Doughnut)的图例右侧添加数字文本,核心是通过自定义图例标签生成函数来实现,具体步骤如下:

1. 准备基础数据

先定义环形图的标签、数值和颜色配置:

const chartData = {
  labels: ['红色', '蓝色', '黄色'],
  datasets: [
    {
      data: [300, 50, 100],
      backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56'],
      hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
    }
  ]
};

2. 配置自定义图例选项

在图表配置项中,通过 plugins.legend.labels.generateLabels 函数自定义每个图例的显示内容,将标签与对应数值拼接:

const chartOptions = {
  plugins: {
    legend: {
      labels: {
        generateLabels: (chart) => {
          const { labels, datasets } = chart.data;
          const targetDataset = datasets[0];
          
          return labels.map((label, idx) => {
            const value = targetDataset.data[idx];
            return {
              text: `${label}: ${value}`, // 拼接标签与数值
              fillStyle: targetDataset.backgroundColor[idx],
              strokeStyle: targetDataset.borderColor?.[idx] || targetDataset.backgroundColor[idx],
              lineWidth: targetDataset.borderWidth || 1
            };
          });
        }
      }
    }
  }
};

3. 渲染环形图组件

注册 Chart.js 必要组件后,使用 Doughnut 组件传入配置好的数据和选项:

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

// 注册环形图所需的核心组件
ChartJS.register(ArcElement, Tooltip, Legend);

export default function CustomLegendDoughnut() {
  return <Doughnut data={chartData} options={chartOptions} />;
}

扩展:显示百分比数值

如果需要显示百分比而非原始数值,可在 generateLabels 中计算占比:

generateLabels: (chart) => {
  const { labels, datasets } = chart.data;
  const targetDataset = datasets[0];
  const totalValue = targetDataset.data.reduce((sum, val) => sum + val, 0);
  
  return labels.map((label, idx) => {
    const value = targetDataset.data[idx];
    const percentage = ((value / totalValue) * 100).toFixed(1) + '%';
    return {
      text: `${label}: ${percentage}`,
      fillStyle: targetDataset.backgroundColor[idx],
      strokeStyle: targetDataset.borderColor?.[idx] || targetDataset.backgroundColor[idx],
      lineWidth: targetDataset.borderWidth || 1
    };
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:27:23