Aggregate Highcharts data in 5-min.
TODO: collapasable, copyable, download, etc
I'm using highcharts. How do I rollup or aggregate my data into 5 minute buckets?To aggregate data into 5-minute buckets using Highcharts, you need to preprocess your data before passing it to the chart. Highcharts itself doesn't provide a direct method for data aggregation, so you'll have to do this in the data preparation phase. Here's a general approach to achieve this in JavaScript:
Prepare Your Data: Ensure your data is in a format that can be easily manipulated. Typically, this would be an array of objects where each object represents a data point with a timestamp and a value.
Sort Your Data: Make sure your data is sorted by the timestamp.
Aggregate the Data: Loop through your sorted data and aggregate it into 5-minute buckets. For each data point, determine the bucket it belongs to and sum or average the values as required.
Create the Final Data Array: The final data array should be in a format that Highcharts can use to render the chart.
Here's an example code snippet to illustrate these steps:
// Sample data array
var data = [
{ timestamp: '2024-01-01T00:00:00', value: 10 },
{ timestamp: '2024-01-01T00:02:00', value: 15 },
// ... more data points
];
// Function to round down a date to the nearest 5 minutes
function roundDownToFiveMinutes(date) {
var minutes = 5 * Math.floor(date.getMinutes() / 5);
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), minutes);
}
// Sorting the data
data.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
// Aggregating the data
var aggregatedData = {};
data.forEach(point => {
var roundedDate = roundDownToFiveMinutes(new Date(point.timestamp));
var key = roundedDate.toISOString();
if (!aggregatedData[key]) {
aggregatedData[key] = { sum: 0, count: 0 };
}
aggregatedData[key].sum += point.value;
aggregatedData[key].count++;
});
// Preparing the final data array for Highcharts
var finalData = [];
for (var key in aggregatedData) {
var avg = aggregatedData[key].sum / aggregatedData[key].count;
finalData.push([new Date(key).getTime(), avg]);
}
// Now, finalData can be used in Highcharts series
In this example, I assumed that you want to average the values in each 5-minute bucket. You can modify the aggregation logic to sum the values or apply any other aggregation method you need. After this, you can use the finalData
array in your Highcharts configuration under the series
data.
Related Chats
Highlighting Graph Area 0.561
Scale Data to New Range 0.398
Smoothly Animate Value with Timestamp 0.383
RRD Data Storage Mechanism 0.364
Extract `key` and `value`. 0.338
Stream REST Data in JavaScript 0.326
Luxon for Human-Friendly Durations 0.322
Predictions with Plugins 0.322
Build Mac App in Xcode 0.319