问题
I'm working with Ionic 3, I'm displaying a bar chart and I need to show data label next to the bar on chart, like this question how to display data values on Chart.js
I followed the instructions I have found so far for chartjs-plugin-datalabels but is not working, it's not showing any data label on my chart.
I installed chartjs and chartjs-plugin-datalabels via npm and they look like this in my package.json
"chart.js": "^2.7.3",
"chartjs-plugin-datalabels": "^0.5.0",
I did the imports just like the docs says to https://chartjs-plugin-datalabels.netlify.com/guide/getting-started.html#integration , but the import line for
import { ChartDataLabels } from 'chartjs-plugin-datalabels';
is showing in VSCode editor as "'ChartDataLabels' is declared but its value is never read"
I've also added inside 'options' a 'plugin' parameter, just like the docs says so, but stills not showing any datalabels.
Here is an extract of my code.
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
}
});
}
回答1:
try enabling the plugin
var chart = new Chart(ctx, {
plugins: [ChartDataLabels],
options: {
// ...
}
})
回答2:
I solved my problem by adding an attribute and passing to it ChartLabel plugin property in class constructor.
import { Chart } from 'chart.js';
import { ChartDataLabels } from 'chartjs-plugin-datalabels';
export class Chart {
chartLabels: any;
constructor( ... ){
this.chartLabels = ChartDataLabels;
}
}
来源:https://stackoverflow.com/questions/54556288/chartjs-plugin-datalabels-not-showing-labels-on-ionic-3