You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Highcharts中基于两个类别对数据进行分组?

解决Highcharts按countType和duration双条件分组展示的问题

要实现按countType和duration组合分组展示数据,核心是先把原始数据整理成Highcharts所需的多系列格式,具体步骤如下:

1. 修正数据字段问题

原始数据中有两条记录的日期字段写为dates(正确应为date),处理时先兼容这个问题,避免数据丢失。

2. 数据分组与格式转换

使用JavaScript的reduce方法,按countType + '-' + duration作为唯一分组键,将每组数据整理成Highcharts支持的[时间戳, 数值]格式:

// 修正后的原始数据(兼容dates字段)
const rawData = [
    {"count":40,"countType":"DISCHARGE","date":"2021-06-11","duration":"ST-15"},
    {"count":27,"countType":"CHARGE","date":"2021-06-11","duration":"ST-15"},
    {"count":23,"countType":"CHARGE","date":"2021-06-12","duration":"ST-15"},
    {"count":23,"countType":"CHARGE","date":"2021-06-14","duration":"ST-15"},
    {"count":40,"countType":"DISCHARGE","date":"2021-06-13","duration":"ST-15"},
    {"count":1,"countType":"DISCHARGEVOLTAGE","date":"2021-06-11","duration":"ST-15"},
    {"count":1,"countType":"DISCHARGEVOLTAGE","date":"2021-06-13","duration":"ST-15"},
    {"count":40,"countType":"DISCHARGE","date":"2021-06-11","duration":"EV1"},
    {"count":40,"countType":"DISCHARGE","date":"2021-06-13","duration":"EV1"},
    {"count":1,"countType":"DISCHARGE","dates":"2021-06-11","duration":"EV1"},
    {"count":6,"countType":"CHARGE","date":"2021-06-11","duration":"EV1"},
    {"count":1,"countType":"CHARGE","dates":"2021-06-12","duration":"EV1"}
];

// 分组并生成Highcharts系列数据
const groupedSeries = rawData.reduce((result, item) => {
    // 统一日期字段,处理拼写错误
    const dateValue = item.date || item.dates;
    const groupKey = `${item.countType}-${item.duration}`;
    
    // 初始化分组
    if (!result[groupKey]) {
        result[groupKey] = {
            name: groupKey,
            data: []
        };
    }
    
    // 将日期转为时间戳,适配Highcharts时间轴
    const timeStamp = new Date(dateValue).getTime();
    result[groupKey].data.push([timeStamp, item.count]);
    
    return result;
}, {});

// 转换为数组格式的series
const chartSeries = Object.values(groupedSeries);

3. 配置Highcharts图表

将生成的chartSeries传入图表配置,同时设置x轴为时间轴类型,自定义日期显示格式:

Highcharts.chart('container', {
    title: {
        text: '按countType和duration分组的数量统计'
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
            day: '%Y-%m-%d'
        },
        title: {
            text: '日期'
        }
    },
    yAxis: {
        title: {
            text: '数量'
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },
    series: chartSeries
});

这样就能实现每个countType+duration组合作为独立系列,在图表中按日期展示对应的count数值。

内容的提问来源于stack exchange,提问作者KnightSky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:20:28