Highcharts双系列多类别条形图按指定系列值排序异常求助
Highcharts条形图按指定系列同步排序解决方法
要实现类别、2022年和2023年数据同步按2023年值排序,不能单独对某一个系列排序——因为类别和其他系列的索引是绑定的,单独排序只会打乱对应关系。正确做法是先把所有关联数据整合后排序,再拆分给图表配置:
步骤1:整合并排序数据
先把类别、两个系列的数据打包成统一数组,按2023年的值排序(这里以降序为例,升序把b.value - a.value反过来即可):
// 原始数据 const originalCategories = ['类别A', '类别B', '类别C', '类别D']; const data2022 = [150, 200, 100, 250]; const data2023 = [300, 180, 220, 280]; // 整合为对象数组 const sortedData = originalCategories.map((name, index) => ({ category: name, val2022: data2022[index], val2023: data2023[index] })).sort((a, b) => b.val2023 - a.val2023); // 按2023年值降序排序
步骤2:拆分排序后的数据
从排序好的数组里提取出对应图表需要的各个部分:
const sortedCategories = sortedData.map(item => item.category); const sortedData2022 = sortedData.map(item => item.val2022); const sortedData2023 = sortedData.map(item => item.val2023);
步骤3:配置到Highcharts
把拆分后的数据替换到图表配置里:
Highcharts.chart('container', { chart: { type: 'bar' }, title: { text: '按2023年值排序的条形图' }, xAxis: { categories: sortedCategories }, series: [ { name: '2022年', data: sortedData2022 }, { name: '2023年', data: sortedData2023 } ] });
这样处理后,类别、2022年和2023年的数据就会完全同步,按2023年的数值排序展示了。
内容的提问来源于stack exchange,提问作者Saif Abbasi
相关产品推荐
相关产品推荐

