传入数据如下,还添加了 highchart 渲染代码和解析指标代码。请检查所附图像,该图像显示一些值之后的 x 轴变得混乱。我们在轴中有很多条目,有没有一种有效的方法来展示其中一些值?
:
Array(4536)
[0 … 99]
0
:
{time: 1713773497767, ampere_hours_of_battery_discharge_per_day: 0, apparent_power_of_load: 0, A_phase_grid_active_power: 0, A_phase_load_rate: 0, …}
1
:
{time: 1713773517767, ampere_hours_of_battery_discharge_per_day: 0, apparent_power_of_load: 0, A_phase_grid_active_power: 0, A_phase_load_rate: 0, …}
2
:
{time: 1713773537768, ampere_hours_of_battery_discharge_per_day: 0, apparent_power_of_load: 0, A_phase_grid_active_power: 0, A_phase_load_rate: 0, …}
3
:
{time: 1713773547768, ampere_hours_of_battery_discharge_per_day: 0, apparent_power_of_load: 0, A_phase_grid_active_power: null, A_phase_load_rate: 0, …}
解析数据的代码如下:
function parseDeviceMetrics(deviceMetrics) {
if (deviceMetrics && typeof deviceMetrics === 'object' && deviceMetrics.status === "SUCCESS") {
// Prepare categories and series for the chart
let categories = [];
let seriesMap = {};
// Assuming deviceMetrics.data is an array of data points
deviceMetrics.data.forEach(dataPoint => {
// Convert timestamp to a Date object
const date = new Date(dataPoint.time);
// Determine the category label based on the current frequency
let categoryLabel;
switch (currentFrequency) {
case 'day':
// Use hours and minutes for daily data
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
categoryLabel = `${hours}:${minutes}`;
break;
case 'week':
case 'month':
// Use full date for weekly or monthly data
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hoursMonth = date.getHours().toString().padStart(2, '0');
const minutesMonth = date.getMinutes().toString().padStart(2, '0');
categoryLabel = `${year}-${month}-${day} ${hoursMonth}:${minutesMonth}`;
break;
default:
// Default to full time string
categoryLabel = date.toLocaleString();
break;
}
// Add category if it's not already included
if (!categories.includes(categoryLabel)) {
categories.push(categoryLabel);
}
// Process each metric in the data point
Object.keys(dataPoint).forEach(metricKey => {
const value = dataPoint[metricKey];
if (metricKey !== 'time' && value !== null) {
if (!seriesMap[metricKey]) {
seriesMap[metricKey] = { name: metricKey, data: [] };
}
seriesMap[metricKey].data.push(value);
}
});
});
// Convert seriesMap to array
let series = Object.values(seriesMap);
console.log("Hie");
console.log(series);
// Sort categories if necessary based on the first category item
if (categories.length > 0 && new Date(categories[0]).getTime()) {
categories.sort((a, b) => new Date(a) - new Date(b));
}
// Prepare formatted data for charting
formattedData = { categories, series };
return formattedData;
} else {
console.error("Failed to fetch device metrics:", deviceMetrics);
}
}
HighChart 代码如下:
function renderChart() {
if (!formattedData.series || !Array.isArray(formattedData.series)) {
console.error('formattedData.series is not an array:', formattedData.series);
return; // Exit the function early to prevent further errors
}
const chartTitleMapping = {
'energyChart': 'Energy Generated',
'stateOfCharge': 'State of Charge',
'packVoltage': 'Pack Voltage',
'systemTemperature': 'System Temperature',
'solarChargeState': 'Solar Charge State'
};
const seriesKey = mapChartTypeToSeriesKey(currentChartType);
// Filter series based on the currentChartType
const series = formattedData.series.filter(s => s.name === seriesKey).map(s => ({
name: chartTitleMapping[currentChartType],
data: s.data
}));
Highcharts.setOptions({
global: {
useUTC: false
}
});
console.log(formattedData.categories);
Highcharts.chart('chartContainer', {
chart: {
type: currentGraphType // Dynamically set chart type (line or bar)
},
title: {
text: chartTitleMapping[currentChartType] || 'Dynamic Chart Title'
},
xAxis: {
type: 'category',
categories: formattedData.categories,
labels: {
"format": "{value}"
}
},
yAxis: {
title: {
text: 'Value' // Customize based on chart type
}
},
series: series.length > 0 ? series : [{ name: 'No data', data: [] }] // Handle case where no series data is available
});
}
如附图所示,x 轴渲染存在什么问题? 渲染如下附图所示:
如果您想呈现数年、数月、数天或数小时的数据,则应使用
xAxis.type: 'datetime'
。然后您应该将数据中的 x 值作为毫秒传递。
演示:https://jsfiddle.net/BlackLabel/tpu5rfog/
API:https://api.highcharts.com/highcharts/xAxis.type
https://api.highcharts.com/highcharts/xAxis.labels.format
https://api.highcharts.com/highcharts/xAxis.dateTimeLabelFormats