Chart.js 2.9.4如何隐藏柱顶数值标签及解决随机NaN%错误问题
问题原因
你当前柱状图顶部的数值标签是由chartjs-plugin-datalabels插件渲染的,Chart.js 2.9.4原生默认不会展示柱顶数值,NaN报错是该插件读取到非法数值、或者数据未完全加载就触发渲染导致的。
解决方案
方案1:直接禁用所有柱顶数值标签(匹配你的需求)
在你的chartOptions配置中新增插件配置项即可,修改后的完整配置如下:
public chartOptions: any = { responsive: true, responsiveAnimationDuration: 0, maintainAspectRatio: false, fill: true, hover: { mode: null }, // 新增插件配置 禁用datalabels plugins: { datalabels: { display: false } }, legend: { position: 'top', align: 'start', labels: { boxWidth: 10, padding: 20, usePointStyle: true } }, tooltips: { mode: 'index', intersect: true }, scales: { xAxes: [{ stacked: true, gridLines: { color: '#D8D8D8' }, scaleLabel: { display: true, labelString: 'Date' }, ticks: { display: true } }], yAxes: [ { id: 'A', position: 'right', scaleLabel: { display: true, labelString: 'Visits' }, ticks: { display: true, beginAtZero: true, autoSkip: true, stepSize: 50, maxTicksLimit: 15 } }, { id: 'B', position: 'left', scaleLabel: { display: true, labelString: 'Users' }, ticks: { display: true, beginAtZero: true, autoSkip: true, stepSize: 5, maxTicksLimit: 15 } } ] } };
如果所有图表都需要禁用,直接修改全局默认配置即可,无需逐个修改图表配置:
在你全局注册chartjs-plugin-datalabels的位置添加以下代码:
import Chart from 'chart.js'; import ChartDataLabels from 'chartjs-plugin-datalabels'; Chart.plugins.register(ChartDataLabels); // 全局设置默认禁用datalabels Chart.defaults.global.plugins.datalabels.display = false;
方案2:保留柱顶标签,仅修复NaN显示问题
如果后续需要展示数值,只需要给datalabels增加格式化回调,对非法值做过滤即可:
plugins: { datalabels: { formatter: (value) => { // 数值非法时返回空字符串,不渲染内容 if (isNaN(value) || value === null || value === undefined) { return ''; } // 按你的原有格式返回数值,比如带百分号 return `${value}%`; } } }
补充注意事项
确保你安装的chartjs-plugin-datalabels版本是1.x版本,2.x及以上版本仅兼容Chart.js 3.x,版本不兼容也可能导致数值渲染异常。
内容的提问来源于stack exchange,提问作者AlleXyS
相关产品推荐
相关产品推荐

