如何使用Chart.js创建Y轴为时间格式的图表?解决绑定报错
问题解决步骤
1. 修复Chart初始化的格式错误
错误Cannot create property 'data' on string '00:00:03.733'的核心原因是datasets参数格式不符合Chart.js要求:它需要是配置对象数组,每个对象必须包含data字段(存储数值型数据),而你直接传入了字符串数组。
先把时间字符串转换为毫秒数值(用于图表计算),同时构建正确的datasets结构:
this.lineBarLabels = []; // 存储转换后的毫秒数值 const timeInMs = []; res.measurements.forEach(element => { this.lineBarLabels.push(element.date); // 将时分秒毫秒字符串转为毫秒数 const timeParts = element.value_time_formatted.split(':'); const seconds = parseFloat(timeParts[2]); const totalMs = parseInt(timeParts[0]) * 3600000 + parseInt(timeParts[1]) * 60000 + seconds * 1000; timeInMs.push(totalMs); }); this.lineBar = new Chart(this.linePresents.nativeElement, { type: 'line', data: { labels: this.lineBarLabels, datasets: [{ label: '测量耗时', // 自定义系列名称 data: timeInMs, borderColor: '#36A2EB', tension: 0.1 }] }, options: { scales: { y: { // 自定义Y轴刻度显示格式,自动把毫秒转时分秒毫秒 ticks: { callback: function(value) { const ms = value as number; const hours = Math.floor(ms / 3600000); const minutes = Math.floor((ms % 3600000) / 60000); const seconds = (ms % 60000) / 1000; // 格式化补零,保留三位小数 return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toFixed(3).padStart(6, '0')}`; } }, title: { display: true, text: '耗时' } } } } }); this.lineBar.update();
2. 关键说明
- 数值转换:必须把时间字符串转为毫秒数,Chart.js只能基于数值绘制折线图,这是图表计算的基础。
- 自动格式化:通过Y轴的
ticks.callback函数,将刻度的毫秒值自动转换为HH:mm:ss.SSS格式,用户无需手动计算。 - datasets结构:每个系列是一个对象,包含
label(图例名称)、data(数值数组)等必要配置,不能直接传入原始字符串数组。
如果需要支持多个测量系列(比如按key分组),可以先按key分组处理数据,再生成多个datasets对象。
内容的提问来源于stack exchange,提问作者mrakodol
相关产品推荐
相关产品推荐

