Primeng 图表使用
Chart.js
作为库,chart.js 在图表上显示数据标签可以使用 chartjs-plugin-datalabels
来完成
首先安装
chartjs-plugin-datalabels
npm i chartjs-plugin-datalabels
然后你需要使用添加插件
import ChartDataLabels from 'chartjs-plugin-datalabels';
在此之后,我们需要创建一个插件数组,其中将包含新安装的库
plugin = [ChartDataLabels];
然后我们添加在正确位置显示标签所需的配置
....
this.basicOptions = {
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
},
...
完整代码
import { Component, OnInit } from '@angular/core';
import ChartDataLabels from 'chartjs-plugin-datalabels';
@Component({
selector: 'chart-basic-demo',
templateUrl: './chart-basic-demo.html',
})
export class ChartBasicDemo implements OnInit {
basicData: any;
plugin = [ChartDataLabels];
basicOptions: any;
ngOnInit() {
const documentStyle = getComputedStyle(document.documentElement);
const textColor = documentStyle.getPropertyValue('--text-color');
const textColorSecondary = documentStyle.getPropertyValue(
'--text-color-secondary'
);
const surfaceBorder = documentStyle.getPropertyValue('--surface-border');
this.basicData = {
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
datasets: [
{
label: 'Sales',
data: [540, 325, 702, 620],
backgroundColor: [
'rgba(255, 159, 64, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(153, 102, 255, 0.2)',
],
borderColor: [
'rgb(255, 159, 64)',
'rgb(75, 192, 192)',
'rgb(54, 162, 235)',
'rgb(153, 102, 255)',
],
borderWidth: 1,
},
],
};
this.basicOptions = {
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
},
legend: {
labels: {
color: textColor,
},
},
},
scales: {
y: {
beginAtZero: true,
ticks: {
color: textColorSecondary,
},
grid: {
color: surfaceBorder,
drawBorder: false,
},
},
x: {
ticks: {
color: textColorSecondary,
},
grid: {
color: surfaceBorder,
drawBorder: false,
},
},
},
};
}
}