如何为Chart.js中y=100的红色水平线添加标注标签?
为Chart.js柱状图的目标水平线添加标注标签解决方案
要让y=100的红色水平线的标注标签正常显示并清晰说明目标值,你需要确保正确引入Chart.js的annotation插件,同时可以优化标签配置让显示效果更合理。以下是调整后的完整代码:
const fetchDataAndRenderChart = (team_band, canvasId, colorIndex) => { fetch(`data.php?team=${team_band}`) .then(response => response.json()) .then(data => { const labels = data.map(item => item.digitiser); const values = data.map(item => item.avg_qc_day); const ctx = document.getElementById(canvasId).getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '日均处理量', data: values, backgroundColor: chartColors[colorIndex].backgroundColor, borderColor: chartColors[colorIndex].borderColor, borderWidth: 1 }] }, options: { plugins: { datalabels: { anchor: 'end', align: 'top', formatter: (value) => value, font: { weight: 'bold' } }, annotation: { annotations: [{ type: 'line', mode: 'horizontal', scaleID: 'y', value: 100, borderColor: 'rgba(255, 99, 132, 0.7)', borderWidth: 3, label: { enabled: true, content: '目标值: 100', position: 'end', backgroundColor: 'rgba(255, 99, 132, 0.2)', font: { weight: 'bold', size: 12 }, padding: 5 } }] } }, scales: { y: { beginAtZero: true } } }, plugins: [ChartDataLabels] }); }) .catch(error => console.error('获取数据出错:', error)); };
关键配置说明
- annotation插件依赖:必须确保已引入该插件,比如通过CDN添加对应脚本,或通过npm安装后导入,否则标注功能无法生效。
- 标签位置优化:将
position设为end,标签会显示在水平线右侧末端,更符合阅读习惯。 - 标签样式增强:添加背景色、调整字体大小和内边距,提升标签的醒目度与可读性。
- 内容适配:将标签内容改为中文表述,适配中文使用场景。
内容的提问来源于stack exchange,提问作者Wathsala Heenkende
相关产品推荐
相关产品推荐

