Chart.js v3中beginAtZero参数设置无效,折线图Y轴无法从0开始
Chart.js Y轴beginAtZero不生效问题解决方案
问题根因
options配置层级错误,Chart.js要求全局配置(包含坐标轴、动画等设置)需要和type、data属性平级,你现在把options写在了datasets数组的单个数据集配置中,所以Y轴的beginAtZero规则没有被正确识别生效。
修正后代码
let atchoum = document.querySelector("#atchoum") let statchoum = new Chart(atchoum, { type: "line", // options移到和type、data平级的位置 options: { responsive: true, scales: { y: { beginAtZero: true } }, animations: { y: { easing: 'easeInOutElastic', from: (ctx) => { if (ctx.type === 'data') { if (ctx.mode === 'default' && !ctx.dropped) { ctx.dropped = true; return 0; } } } } }, }, data: { labels: {{ atchoumDate|raw }}, datasets: [{ label: "Nombre d'éternuements au support", data: {{ atchoumNb|raw }}, borderColor: "blue", tension: 0.3 }] } })
额外兼容提示
如果修改后还是不生效,检查你使用的Chart.js版本:
- 3.x及以上版本Y轴配置键为
y,上述代码直接可用 - 2.x版本Y轴配置需要调整为:
scales: { yAxes: [{ ticks: { beginAtZero: true } }] }
内容的提问来源于stack exchange,提问作者Huri
相关产品推荐
相关产品推荐

