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

Angular中如何在Chart.js环形图(doughnut)的每个扇区内显示数据

解决方案

你当前代码的核心问题有三个:

  • 没有正确安装引入chartjs-plugin-datalabels插件
  • dougnutChartPlugins配置错误,你传入的是标签数组而非插件实例
  • 未配置datalabels的显示格式化规则,且doughnutChartData为空没有实际渲染数据

可按以下步骤修改:

步骤1:安装依赖

npm install chartjs-plugin-datalabels --save

注意版本匹配:如果你的项目用的是Chart.js 3.x版本,安装2.x版的datalabels;如果是Chart.js 2.x,安装1.x版的datalabels。

步骤2:修改TypeScript代码

首先导入插件,再修正相关配置项:

// 顶部导入datalabels插件
import * as DataLabels from 'chartjs-plugin-datalabels';

public doughnutChartLabels: string[] = [
  'Demo',
  'Test',
  'Live',
];

// 修正plugins配置,传入插件实例
public dougnutChartPlugins = [DataLabels];
public doughnutChartLegend = true;
// 填充实际数据,格式为数组包裹对象,对象内data为对应标签的数值
doughnutChartData = [
  {
    data: [35, 45, 20] // 这里替换为你的实际业务数据
  }
];

public doughnutChartColors: any[] = [
  {
    backgroundColor: ['#735A84', '#E76412', '#9BC311'],
  },
];

public doughnutChartType = 'doughnut';
public doughnutChartOptions: any = {
  animation: false,
  responsive: true,
  maintainAspectRatio: true,
  plugins: {
    datalabels: {
      // 设置标签颜色为白色,避免和扇区背景撞色
      color: '#fff',
      font: {
        weight: 'bold',
        size: 19
      },
      // 配置显示规则,示例为显示占比百分比,如需显示原始数值直接return value即可
      formatter: (value: number, ctx: any) => {
        const total = ctx.dataset.data.reduce((a: number, b: number) => a + b, 0);
        const percentage = Math.round((value / total) * 100);
        return `${percentage}%`;
      }
    }
  }   
};

步骤3:HTML代码无需调整

你现有HTML代码结构正确,保持即可:

<canvas baseChart class="chart" [data]="doughnutChartData" [labels]="doughnutChartLabels"
  [options]="doughnutChartOptions" [chartType]="doughnutChartType"                      
  [legend]="doughnutChartLegend"
  [plugins]="dougnutChartPlugins"
  [colors]="doughnutChartColors">
</canvas>

修改完成后重新运行项目即可实现扇区内直接显示数据的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:45:03