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

如何在react-chartjs-2环形图中添加百分比数值及下方子标签

解决方案

你需要借助chartjs-plugin-datalabels插件实现扇区内双行自定义标签的效果,具体操作步骤如下:

1. 安装依赖插件

react-chartjs-2本身不内置扇区内自定义标签功能,需要安装对应插件实现:

# npm 安装
npm install chartjs-plugin-datalabels
# 或 yarn 安装
yarn add chartjs-plugin-datalabels

版本适配提示:若使用react-chartjs-2 v4及以上版本(对应Chart.js v3+),请安装v2.x版本的datalabels插件;更低版本的react-chartjs-2适配v1.x版本插件

2. 注册插件

在环形图对应的组件文件顶部注册所需插件:

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

// 注册Chart.js基础组件和标签插件
ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);

3. 调整图表配置

修改你原有的mainChart配置,新增插件相关参数,完整配置示例如下:

mainChart: {
  datasets: [], // 保留你原有的数据集配置即可
  options: {
    cutoutPercentage: 66,
    spanGaps: false,
    legend: {
      display: true,
      position: "right",
      labels: {
        padding: 16,
        usePointStyle: true,
        generateLabels:function(chart){
          const labels=["de 0 à 4", "+4j", "+15J", "+45J", "+90J", "+150J"];
          // 补充返回值结构,保证图例正常显示
          return labels.map((label, i) => ({
            text: label,
            fillStyle: chart.data.datasets[0].backgroundColor[i],
            strokeStyle: chart.data.datasets[0].backgroundColor[i],
            index: i
          }))
        }
      }
    },
    maintainAspectRatio: false,
    // 新增标签插件配置
    plugins: {
      datalabels: {
        color: '#fff', // 标签文字颜色,可按需调整
        anchor: 'center',
        align: 'center',
        offset: 0,
        // 返回数组即可实现上下双行标签效果
        formatter: (value, ctx) => {
          // 计算百分比
          const total = ctx.chart.data.datasets[0].data.reduce((sum, val) => sum + val, 0);
          const percentage = Math.round((value / total) * 100) + '%';
          // 第一行百分比,第二行对应子标签
          return [percentage, ctx.chart.data.labels[ctx.dataIndex]];
        },
        font: {
          weight: 'bold',
          size: 14
        },
        textAlign: 'center',
        lineHeight: 1.5 // 调整两行文字的间距
      }
    }
  }
}

4. 组件调用保持不变

你原有的Doughnut组件调用代码无需修改,直接使用即可:

<Doughnut
  data={{ 
    labels: data.mainChart.labels,
    datasets: data.mainChart.datasets
  }}
  options={data.mainChart.options}
/>

如果出现标签不显示的情况,优先检查插件版本是否匹配、是否已经完成注册即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:18:02