Chart.js中chartjs-plugin-datalabels数据标签显示异常求助
解决Chart.js水平条形图数据标签仅显示主数值的问题
问题原因
你的每个数据点是以{x: 数值, y: i}的对象格式定义的,chartjs-plugin-datalabels插件默认会将整个对象转为字符串输出,因此出现了x: 222, y: 1这类格式的标签。
解决方法
只需在plugins.datalabels配置中添加formatter回调函数,提取数据点的x属性值即可。修改后的完整代码如下:
Chart.register(ChartDataLabels); new Chart('myChart', { type: 'bar', plugins: [{ afterInit: chart => { let dataset = chart.data.datasets[0]; chart.data.datasets = chart.data.labels.map((l, i) => ({ label: l, data: [{ x: dataset.data[i], y: i }], backgroundColor: dataset.backgroundColor[i], categoryPercentage: 1 })); chart.data.labels = undefined; }, beforeLayout: chart => { chart.options.scales.y1.labels = chart.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label); } }], data: { labels: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black'], datasets: [{ data: [123, 321, 213, 111, 222, 333, 234, 444], backgroundColor: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black'] }] }, options: { indexAxis: 'y', maintainAspectRatio: false, plugins: { datalabels: { color: 'white', // 新增formatter函数提取主数值 formatter: (value) => value.x }, legend: { position: 'top' }, tooltip: { callbacks: { title: () => null } } }, scales: { x: { title: { display: true, text: 'xAxis' } }, y: { display: false, }, y1: { title: { display: true, text: 'yAxisLabel' }, offset: true } } }, });
关键说明
formatter函数接收当前数据点的value参数(即你定义的{x: 数值, y: i}对象),直接返回value.x就能让标签仅显示主数值。
内容的提问来源于stack exchange,提问作者Aishwarya
相关产品推荐
相关产品推荐

