ChartJS插件数据标签未在Ionic 3上显示标签

问题描述 投票:1回答:2

我正在使用Ionic 3,我正在显示条形图,我需要在图表上的条形图旁边显示数据标签,就像这个问题how to display data values on Chart.js

我按照目前为止找到的chartjs-plugin-datalabels的说明进行了操作,但是没有工作,它没有在我的图表上显示任何数据标签。

我通过npm安装了chartjs和chartjs-plugin-datalabels,它们在我的package.json中看起来像这样

"chart.js": "^2.7.3",
"chartjs-plugin-datalabels": "^0.5.0",

我做的进口就像文档对https://chartjs-plugin-datalabels.netlify.com/guide/getting-started.html#integration说的那​​样,但进口线为

import { ChartDataLabels } from 'chartjs-plugin-datalabels'; 

在VSCode编辑器中显示“'ChartDataLabels'已声明,但其值永远不会被读取”

我还在内部'选项'中添加了'插件'参数,就像文档所说的那样,但仍然没有显示任何数据标签。

这是我的代码的摘录。

import { Component, ViewChild, ɵConsole } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, App } from 'ionic-angular';
import { Chart } from 'chart.js';  
import { ChartDataLabels } from 'chartjs-plugin-datalabels';


@ViewChild('barCanvas') barCanvas;

ionViewDidLoad() {
 this.barChart = new Chart(this.barCanvas.nativeElement, {
  type: 'bar',
  data: {
    labels: [..],
    datasets: [
      {
        label: "Ok",
        data: arrayOk,
        backgroundColor: '#014582',
        borderWidth: 1,
        datalabels: {
          align: 'end',
          anchor: 'start'
        }
      },
      {
        label: "Not Okay",
        data: arrayNotOk,
        backgroundColor: '#777676',
        borderWidth: 1,
        datalabels: {
          align: 'center',
          anchor: 'center'
        }
      }],
  },
  options: {
    plugins: {
      datalabels: {
        color: 'white',
        display: function (context) {
          return context.dataset.data[context.dataIndex] > 1;
        },
        font: {
          weight: 'bold'
        },
        formatter: Math.round,

        title: false
      }
    },
    title: {
      display: true,
      position: "top",
      text: "My Bar Chart with Datalabels",
      fontSize: 18,
      fontColor: "#111"
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        ticks: {
          autoSkip: false
        }
      }]
    },
    legend: false
  }
});
}
angular ionic3 chart.js2
2个回答
1
投票

尝试启用插件

    var chart = new Chart(ctx, {
        plugins: [ChartDataLabels],
        options: {
            // ...
        }
    })

1
投票

我通过添加一个属性并在类构造函数中传递ChartLabel插件属性来解决我的问题。

import { Chart } from 'chart.js';
import { ChartDataLabels } from 'chartjs-plugin-datalabels';

export class Chart {

  chartLabels: any;

  constructor( ... ){
    this.chartLabels = ChartDataLabels;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.