如何在LWC的ChartJS水平堆叠单条形图下方显示数据集标签
实现水平堆叠条形图下方显示数据集标签(ChartJS v2.8.0 + LWC)
针对你的需求,要在水平堆叠单条形图的每个条形下方显示对应的数据集标签(Completed、In Progress、Waiting),可以通过调整chartjs-plugin-datalabels的配置来实现,同时修正原有代码中的几个小问题:
关键修改点
修正ChartJS v2配置错误:
- 移除
indexAxis: 'x':ChartJS v2中horizontalBar类型默认就是水平方向,该配置是v3版本新增的,v2不支持 - 修正拼写错误:
resposive改为responsive
- 移除
配置datalabels插件显示数据集标签:
- 通过
formatter回调指定显示数据集的label而非默认数值 - 设置
position: 'bottom'让标签显示在条形下方,align: 'center'保证标签与条形居中对齐 - 调整
offset控制标签与条形的间距,通过font配置优化标签样式
- 通过
修改后的完整代码
Chart.plugins.register(ChartDataLabels); new Chart( document.getElementById('myChart'), { type: 'horizontalBar', data: { labels: ["#count"], datasets: [ { label: 'Completed', barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, backgroundColor: "blue", data: [10], }, { label: 'In Progress', barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, backgroundColor: "orange", // 建议区分颜色便于识别 data: [65], }, { label: 'Waiting', barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, backgroundColor: "gray", // 建议区分颜色便于识别 data: [80], }, ] }, options: { responsive: true, scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] }, plugins: { datalabels: { clamp: true, color: "black", position: 'bottom', // 标签位置:条形下方 align: 'center', // 标签与条形居中对齐 offset: 10, // 标签与条形的间距 formatter: function(value, context) { // 返回当前数据集的label return context.dataset.label; }, font: { weight: "bold", size: 12 } } } } });
额外建议
- 给不同数据集设置不同的
backgroundColor,能更直观地区分每个条形对应的状态 - 如果标签显示位置仍需微调,可以调整
offset数值或修改align为'left'/'right'适配需求
内容的提问来源于stack exchange,提问作者Sagar
相关产品推荐
相关产品推荐

