如何在Angular的Ng2Chart中为Chart.js柱状图添加数据标签
在Angular的Chart.js柱状图中添加柱子内的数据标签
要给每个柱状条显示对应数值,Chart.js本身没有内置这个功能,需要用官方的chartjs-plugin-datalabels插件,具体实现步骤如下:
步骤1:安装插件
在项目根目录执行命令:
npm install chartjs-plugin-datalabels --save
步骤2:导入插件并修改组件代码
在bar.component.ts顶部导入插件:
import ChartDataLabels from 'chartjs-plugin-datalabels';
然后修改createChart方法,注册插件并配置数据标签的显示规则(适配横向/纵向柱状图):
createChart() { this.chart = new Chart(this.id, { type: 'bar', plugins: [ChartDataLabels], // 注册数据标签插件 data: { labels: this.labels, datasets: [ { data: this.values, backgroundColor: this.backgroundColors, hoverBackgroundColor: this.backgroundColors, hoverBorderColor: this.backgroundColors, barThickness: this.barThickness, } ] }, options: { responsive: true, indexAxis: this.barBaseAxis, // Base Axis. scales: { x: { grid: { //Hide background lines. display: false, drawBorder: this.xAxisLableVisiable }, ticks: { // For hide Lables on Y-axis. display: this.xAxisLableVisiable } }, y: { grid: { display: false, drawBorder: this.xAxisLableVisiable }, ticks: { // For hide Lables on Y-axis. display: this.yAxisLableVisiable }, } }, plugins: { legend: { // Hide top lables. display: this.barTitleLable }, tooltip: { // Hover tooltip enabled: this.barTooltipEnable }, datalabels: { display: this.displayDetailOfData, // 用现有输入参数控制标签是否显示 // 根据柱状图方向调整标签位置 align: this.barBaseAxis === 'x' ? 'center' : 'end', anchor: this.barBaseAxis === 'x' ? 'center' : 'center', color: '#000', // 标签文字颜色,可自定义 font: { weight: 'bold', size: 12 }, // 自定义数值格式,这里直接显示原始值 formatter: (value: number) => value } } } }); }
说明
- 插件配置里的
display绑定了现有输入参数displayDetailOfData,保持原有组件的可控性 - 根据
barBaseAxis的值自动调整标签的对齐方式,适配纵向(x轴为基准)和横向(y轴为基准)柱状图 - 可以根据需求修改
color、font、formatter等属性,自定义标签样式和显示格式
内容的提问来源于stack exchange,提问作者ErDeep
相关产品推荐
相关产品推荐

