Chart.js双Y轴折线图第二数据集未绑定指定轴导致渲染异常问题
问题根源定位
你的配置失效核心原因是数据集绑定Y轴的属性名拼写错误:
- 你在两个数据集里写的绑定属性是
yAxesID(使用了复数形式Axes) - Chart.js v3+ 版本用于指定数据集对应Y轴的正确属性为
yAxisID(单数形式Axis,无末尾多余的s)
这个拼写错误会导致Chart.js完全无法识别你指定的轴绑定关系,默认把所有数据集都匹配到第一个配置的y轴上,最终数值范围0-10000的Score数据集被按0-100的左轴规则缩放,直接超出可视区域不可见。
修正方案
只需要把两个数据集里写错的yAxesID替换为正确的yAxisID即可,其余原有配置不需要强制调整。修正后的可运行代码如下:
const CHART = document.getElementById("statChart"); let statChart = new Chart(CHART, { type: 'line', data: { labels: ["1", "2", "3", "4", "5", "6", "7"], datasets: [ { type: 'line', label: "Completed", // 修正:替换为正确的yAxisID yAxisID: 'y', fill: false, lineTension: 0.1, backgroundColor: "rgba(75, 192, 192, 0.4)", borderColor: "rgba(75, 192, 192, 1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40] }, { type: 'line', label: "Score", // 修正:替换为正确的yAxisID yAxisID: 'y1', fill: false, lineTension: 0.1, // 建议调整两个折线的颜色,避免视觉混淆 backgroundColor: "rgba(255, 159, 64, 0.4)", borderColor: "rgba(255, 159, 64, 1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(255,159,64,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHitRadius: 10, data: [8500, 8900, 8000, 8100, 5600, 5500, 4900] } ]}, options: { responsive: true, interaction: { mode: 'index', intersect: false, }, plugins: { title: { display: true, text: 'Your Result' }, tooltips: { mode: 'nearest', intersect: true, } }, scales: { y: { type: 'linear', display: true, position: 'left', min: 0, max: 100 }, y1: { type: 'linear', display: true, position: 'right', min: 0, max: 10000, grid: { drawOnChartArea: false, } } } } });
附加说明:修正配置后,你原代码中两个折线的样式完全一致,在同图表中会难以区分,上述代码额外调整了Score数据集的配色,可按需保留或修改。
内容的提问来源于stack exchange,提问作者user3241329
相关产品推荐
相关产品推荐

