如何在ChartJS中将同小时的数据合并为单个柱状图?
实现ChartJS小时级数据聚合展示
要让同一小时的数据合并为单个柱状图,你需要先预处理原始数据,把同一小时的y值求和后再传给ChartJS——因为ChartJS本身不会自动完成数据聚合。
1. 编写数据聚合函数
这个函数会把原始时间数据按小时分组,计算每个小时的总数值:
function aggregateHourlyData(rawData) { const hourlyMap = new Map(); rawData.forEach(item => { // 将时间字符串转为Date对象,提取当前小时的起始时间点 const date = new Date(item.x); const hourStart = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours()); // 用ISO格式字符串作为分组键,确保同一小时的所有数据被归为一组 const hourKey = hourStart.toISOString(); if (hourlyMap.has(hourKey)) { hourlyMap.set(hourKey, hourlyMap.get(hourKey) + item.y); } else { hourlyMap.set(hourKey, item.y); } }); // 转换为ChartJS需要的{x,y}格式数组 return Array.from(hourlyMap.entries()).map(([x, y]) => ({ x, y })); }
2. 修改ChartJS配置
用聚合后的数据替换原始数据,同时调整颜色和交互配置:
// 原始数据 const rawChartData = [ {x: '2022-10-03T07:43:00', y: 1}, {x: '2022-10-03T07:50:00', y: 1}, {x: '2022-10-03T08:30:00', y: 1}, {x: '2022-10-03T08:10:00', y: 1}, {x: '2022-10-03T09:15:30', y: 1}, {x: '2022-10-03T09:30:00', y: 1}, {x: '2022-10-03T10:05:00', y: 1}, {x: '2022-10-03T10:10:00', y: 1}, {x: '2022-10-03T10:45:00', y: 1}, {x: '2022-10-03T15:15:00', y: 1}, ]; // 聚合小时数据 const aggregatedData = aggregateHourlyData(rawChartData); // 初始化Chart let chart = new Chart(document.getElementById('peh-bar-chart').getContext('2d'), { type: 'bar', data: { datasets: [{ label: '# of Votes', data: aggregatedData, // 使用聚合后的数据 backgroundColor: 'rgba(54, 162, 235, 0.2)', // 统一颜色,也可以用数组循环多色 borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }] }, options: { scales: { xAxes: [{ type: 'time', time: { unit: 'hour', displayFormats: { hour: 'hA' // 显示格式调整为7AM、8AM这类形式 } }, scaleLabel: { display: true, labelString: '时间' } }], yAxes: [{ scaleLabel: { display: true, labelString: '投票数' }, ticks: { beginAtZero: true // y轴从0开始,更直观展示数据 } }] }, tooltips: { callbacks: { // 自定义hover提示内容,明确显示总数值 label: function(tooltipItem) { return `总票数: ${tooltipItem.yLabel}`; } } } } });
关键细节说明
- ChartJS的时间轴仅负责刻度渲染,不会自动聚合数据,必须提前对原始数据做分组求和处理。
- 聚合函数中用
hourStart获取每个小时的起始时间(比如7点数据统一归到2022-10-03T07:00:00),确保同一小时的所有数据被正确分组。 - 如果需要给不同小时的柱子设置不同颜色,把
backgroundColor改成颜色数组即可,ChartJS会自动循环使用数组内的颜色。
内容的提问来源于stack exchange,提问作者hussaindev53
相关产品推荐
相关产品推荐

