Chartjs使用角甜甜圈不返回格式化程序函数来显示标签和值

zpgglvta  于 2023-08-05  发布在  Chart.js
关注(0)|答案(1)|浏览(164)

我想在数据集段附近的图形周围显示标签名称和值。我写了一个格式化函数,它没有返回。look into the below link is my requirement但是我不能返回图this is what I got but not returning label and values周围的标签和值

import { Component, OnInit } from '@angular/core';
import { Chart, ChartOptions, ChartDataset, ChartConfiguration } from 'chart.js';
import 'chartjs-plugin-datalabels';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})

export class YourComponent implements OnInit {
  chart: Chart;
  ngOnInit(): void {
    this.createChart();
  }
  createChart(): void {
    const data: ChartDataset[] = [
      {
        data: [10, 20, 15, 5, 50],
        backgroundColor: [
          'rgb(255, 99, 132)',
          'rgb(255, 159, 64)',
          'rgb(255, 205, 86)',
          'rgb(75, 192, 192)',
          'rgb(54, 162, 235)',
        ],
      },
    ];

    const options: ChartOptions = {
      plugins: {
        datalabels: {
          formatter: function (value, context) {
            const label = context.chart.data.labels[context.dataIndex];
            return label + ': ' + value + '%';
          },
          anchor: 'end',
          align: 'end',
          offset: 10,
          color: 'black',
          font: {
            size: 12,
          },
        },
      },
    };

    const config: ChartConfiguration = {
      type: 'doughnut',
      data: {
        datasets: data,
        labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
      },
      options: options,
    };

    const canvas = document.getElementById('myChart') as HTMLCanvasElement;

    this.chart = new Chart(canvas, config);

  }
}

字符串

ve7v8dk2

ve7v8dk21#

chartjs-plugin-datalabels 文档中,您需要全局或本地注册插件]。
全球注册:

import ChartDataLabels from 'chartjs-plugin-datalabels';

Chart.register(ChartDataLabels);

字符串
或在本地注册:

import ChartDataLabels from 'chartjs-plugin-datalabels';

const config: ChartConfiguration = {
  type: 'doughnut',
  data: {
    datasets: data,
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
  },
  options: options,
  plugins: [ChartDataLabels] // Register locally
};


Demo @ StackBlitz

相关问题