Highcharts分组堆叠柱状图消除重复图例、合并同名系列实现
同名图例聚合实现方案
完全可以通过Highcharts原生配置实现,不需要改动现有分组堆叠逻辑,按以下步骤调整即可达成需求:
- 统一同名系列样式并隐藏冗余图例
给所有名称相同的系列(如所有Confirmed、Potential系列)手动设置一致的color,保证图例颜色和所有堆叠块颜色匹配;给除首个出现外的所有同名系列添加showInLegend: false配置,直接隐藏重复的图例项。 - 自定义图例点击联动逻辑
给需要显示在图例中的同名主系列,重写legendItemClick事件,点击图例时同步控制所有同名系列的显示/隐藏状态,需额外阻止默认仅隐藏当前系列的行为。 - (可选)添加图例hover联动
给主系列追加图例hover相关事件,实现鼠标悬浮图例时,所有同名堆叠块同步高亮的效果。
修改后的完整初始化代码
$(function () { $('#container').highcharts({ chart: { type: 'bar' }, title: { text: 'Total fruit consumtion, grouped by gender' }, xAxis: { categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'] }, yAxis: { allowDecimals: false, min: 0, title: { text: 'Number of fruits' } }, tooltip: { formatter: function() { return '<b>'+ this.x +'</b><br/>'+ this.series.name +': '+ this.y +'<br/>'+ 'Total: '+ this.point.stackTotal; } }, plotOptions: { bar: { stacking: 'normal' } }, series: [ { name: "Confirmed", stack: "ACTIVE", color: '#7cb5ec', // 统一所有Confirmed系列颜色 data: [4740, 1378, 8], events: { legendItemClick: function() { const targetName = this.name; // 遍历所有系列,同步控制同名系列显隐 this.chart.series.forEach(s => { if(s.name === targetName) { s.visible ? s.hide() : s.show(); } }) return false; // 阻止默认仅隐藏当前系列的行为 }, // 可选:hover图例时高亮所有同名系列 legendItemMouseOver: function() { const targetName = this.name; this.chart.series.forEach(s => { if(s.name === targetName) s.setState('hover'); }) }, legendItemMouseOut: function() { const targetName = this.name; this.chart.series.forEach(s => { if(s.name === targetName) s.setState(); }) } } }, { data: [2932, 141], name: "Potential", stack: "ACTIVE", color: '#90ed7d', // 统一所有Potential系列颜色 events: { legendItemClick: function() { const targetName = this.name; this.chart.series.forEach(s => { if(s.name === targetName) { s.visible ? s.hide() : s.show(); } }) return false; }, legendItemMouseOver: function() { const targetName = this.name; this.chart.series.forEach(s => { if(s.name === targetName) s.setState('hover'); }) }, legendItemMouseOut: function() { const targetName = this.name; this.chart.series.forEach(s => { if(s.name === targetName) s.setState(); }) } } }, { data: [1752, 11], name: "Confirmed", stack: "REOPENED", showInLegend: false, // 隐藏冗余图例 color: '#7cb5ec' }, { data: [1089, 2], name: "Potential", stack: "REOPENED", showInLegend: false, color: '#90ed7d' }, { data: [2332, 1960, 42], name: "Potential", stack: "NEW", showInLegend: false, color: '#90ed7d' }, { data:[480, 4684, 2258], name: "Confirmed", stack: "NEW", showInLegend: false, color: '#7cb5ec' } ] }); });
配置完成后,图例区域只会保留唯一的系列名称项,点击图例时会同步控制所有对应名称的堆叠块显隐,hover时也会同步高亮所有同名称的堆叠区块,完全匹配聚合展示的需求。
内容的提问来源于stack exchange,提问作者user1234
相关产品推荐
相关产品推荐

