Chart.js中Y轴刻度min与max设置无效问题求助
问题根源:版本冲突 + 配置结构不匹配
你遇到的Y轴刻度范围设置无效的问题,核心原因有两个:
1. 同时引入了Chart.js的两个版本
你页面里同时加载了Chart.js 2.9.4和3.0.0版本:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
这会导致版本冲突,实际生效的是后加载的3.0.0版本,但你用的是2.x版本的配置语法,自然无法生效。
2. Chart.js 3.x和2.x的Y轴配置结构差异极大
2.x版本里是通过scales.yAxes数组来配置Y轴,但3.x版本已经把轴的配置改成了对象形式,直接用scales.y来配置。另外需要注意:3.x里min和max更推荐直接配置在scales.y根节点下(而非ticks内部)。
解决步骤
第一步:移除冗余的Chart.js版本
只保留一个版本(推荐保留3.0.0,因为你用到的chartjs-plugin-datalabels@2.0.0适配Chart.js 3.x):
<!-- 只保留这个3.0.0版本,删掉2.9.4的引入 --> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
第二步:修正Y轴配置结构
把原来2.x风格的scales.yAxes改成3.x的scales.y结构:
scales: { y: { min: -100, // 直接设置在y轴配置根节点 max: 100, ticks: { // 其他刻度相关配置可放在这里 } } }
另外你还重复引入了chartjs-plugin-datalabels的两个版本,建议只保留稳定版@2.0.0,避免不必要的冲突。
修正后的完整代码
<!DOCTYPE html> <html> <head> <!-- 只保留Chart.js 3.0.0版本 --> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script> <!-- 只保留一个datalabels插件版本 --> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script> <title>daily</title> </head> <body> <canvas class='temp_chart' id='temp_chart'></canvas> <script> function square_data(chart){ var c = document.createElement("canvas"); var ctx = c.getContext("2d"); ctx.fillStyle = "#FFA500"; ctx.rect(145, 70, 15, 15); ctx.fill(); ctx.fillStyle = "#fff"; ctx.fillText(chart.dataset.data[chart.dataIndex], 147,82, 10); ctx.stroke(); return c; } const time_of_day = ['Morning', 'Day', 'Evening', 'Night'] var temperatures = [15, 18, 4, -6] var ctx = document.getElementById('temp_chart').getContext('2d') window.chart = new Chart(ctx, { type: 'line', data: { labels: time_of_day, datasets: [{ fill:false, label: 'Cantidad Estudiantes', data: temperatures, borderColor: [ 'rgba(0, 0, 0, 1)', ], borderWidth: 3 }] }, options: { plugins: { legend: { display: false, }, datalabels: { anchor: 'start', align: '-45', clamp: true, color: "orange", } }, elements:{ "point":{"pointStyle":square_data}, }, // 修正后的3.x风格Y轴配置 scales: { y: { min: -100, max: 100 } } } }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者MGR4
相关产品推荐
相关产品推荐

