Chart.js自动更新时X轴顺序错乱问题求助
问题解决:Chart.js自动更新时X轴顺序异常
问题出在你使用了默认的category类型X轴,这种轴是为离散分类设计的,并不适配时间序列数据。Chart.js会自动收集所有X值生成分类列表,并按字符串升序排列——即便你的时间字符串格式是递增的,也可能因分类生成逻辑的问题导致顺序异常,最终最新数据出现在左侧。
解决方案:改用Time类型X轴
Chart.js 3.x及以上版本已内置时间轴支持,无需额外加载插件,直接将X轴配置为time类型即可:
修改图表配置中scales.x部分:
x: { type: 'time', time: { parser: 'YYYY-MM-DD HH:mm:ss', // 匹配你生成的时间字符串格式 tooltipFormat: 'YYYY-MM-DD HH:mm:ss', unit: 'second', // 数据间隔为2秒,设置为秒级显示 displayFormats: { second: 'YYYY-MM-DD HH:mm:ss' // 刻度显示格式 } }, ticks: { maxRotation: 90, minRotation: 45 } }
修改后的完整代码
let dt2str = function (d, as_utc = false) { let Y = (as_utc === true ? d.getUTCFullYear() : d.getFullYear()).toString(); let M = ((as_utc === true ? d.getUTCMonth() : d.getMonth()) + 1) .toString() .padStart(2, 0); let D = (as_utc === true ? d.getUTCDate() : d.getDate()) .toString() .padStart(2, 0); let h = (as_utc === true ? d.getUTCHours() : d.getHours()) .toString() .padStart(2, 0); let m = (as_utc === true ? d.getUTCMinutes() : d.getMinutes()) .toString() .padStart(2, 0); let s = (as_utc === true ? d.getUTCSeconds() : d.getSeconds()) .toString() .padStart(2, 0); let dstr = `${Y}-${M}-${D} ${h}:${m}:${s}`; return dstr; }; let ctx = document.getElementById("chart"); let chart = new Chart(ctx, { type: "line", data: { datasets: [ { yAxisID: "yAxis1", label: "a", data: [], borderWidth: 1, spanGaps: true, tension: 0 }, { yAxisID: "yAxis2", label: "b", data: [], borderWidth: 1, spanGaps: true, tension: 0 } ] }, options: { scales: { x: { type: 'time', time: { parser: 'YYYY-MM-DD HH:mm:ss', tooltipFormat: 'YYYY-MM-DD HH:mm:ss', unit: 'second', displayFormats: { second: 'YYYY-MM-DD HH:mm:ss' } }, ticks: { maxRotation: 90, minRotation: 45 } }, yAxis1: { type: "linear", display: true, position: "left" }, yAxis2: { type: "linear", display: true, position: "right", grid: { drawOnChartArea: false } } } } }); setInterval(() => { let xtime = dt2str(new Date()); chart.data.datasets.forEach((d) => { d.data.push({ x: xtime, y: Math.floor(Math.random() * 10) }); }); chart.update(); }, 2000);
原理说明
Time轴专门针对时间序列数据设计,会自动解析你的时间字符串并按时间先后顺序排列刻度,新添加的最新数据会自然显示在图表右侧,完全符合预期。而category轴是为静态分类设计的,无法正确处理动态递增的时间数据。
内容的提问来源于stack exchange,提问作者wpsd
相关产品推荐
相关产品推荐

