Highcharts多系列饼图如何实现单图例点击同步控制双系列显隐
解决方案
实现思路
要实现你的需求只需两步调整:
- 仅保留第一个系列的图例显示,第二个系列设置
showInLegend: false避免图例重复 - 绑定图例点击事件,点击单个图例项时,同步切换两个系列中同名数据点的显隐状态
调整后的完整代码
Highcharts.chart('container', { chart: { marginTop:-30, marginBottom:90, height:300, type:'pie' }, title:{ text:'' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { shadow: false, center: ['50%', '50%'], point: { events: { legendItemClick: function(e) { const pointName = this.name; const chart = this.series.chart; // 遍历所有系列,同步切换同名点的显隐 chart.series.forEach(series => { const targetPoint = series.points.find(p => p.name === pointName); if(targetPoint) { targetPoint.setVisible(!targetPoint.visible, false); } }); // 重绘图表 chart.redraw(); // 阻止默认点击行为,避免重复处理 return false; } } } }, }, colors: ['#55d8fe', '#fd8373', '#feda83','#a3a0fb', '#69F0AE', '#E1BEE7','#B2DFDB', '#C5E1A5', '#F8BBD0', '#E6EE9C', '#C6FF00', '#FFF176'], series: [{ name: 'New Projects', size: '60%', showInLegend: true, data: [{name: "Digital 1", y: 5.25}, {name: "Digital 2", y: 0}, {name: "FW", y: 13.48}, {name: "M-signal", y: 17.19}, {name: "OPS", y: 1.52}, {name: "Other", y: 12.4}, {name: "S/W", y: 10.82}, {name: "Systems", y: 11.3} ], dataLabels: { enabled: true, formatter: function () { let per = this.point.percentage.toFixed(1)+'%'; return this.point.percentage !=0?per:null; }, distance: -30, shadow:false, style: { fontWeight: 'normal', color: '#555', textOutline:0 } }, }, { name: 'Ref. Project', innerSize: '60%', size: '80%', showInLegend: false, // 关闭第二个系列的图例显示,避免重复 data: [{name: "Digital 1", y: 6.17}, {name: "Digital 2", y: 32.31}, {name: "FW", y: 11.01}, {name: "M-signal", y: 20.15}, {name: "OPS", y: 1.06}, {name: "Other", y: 13.12}, {name: "S/W", y: 7.34}, {name: "Systems", y: 8.84}], dataLabels: { enabled: true, formatter: function () { let per = this.point.percentage.toFixed(1)+'%'; return this.point.percentage !=0?per:null; }, distance: -15, shadow:false, style: { fontWeight: 'normal', color: '#555', textOutline:0 } }, }], legend: { align: 'left', x: 0, y:10, itemMarginTop:7, marginBottom:40, itemStyle: { fontSize:'12px', fontWeight: 'normal' }, symbolHeight: 15, symbolWidth: 15, symbolRadius: 0, symbolPadding:10 }, credits: { enabled: false } });
改动点说明
- 第二个系列的
showInLegend属性改为false,去掉重复图例 - 新增
legendItemClick事件处理逻辑,点击图例时遍历所有系列的点,匹配到同名称的点后同步切换显隐,最后统一重绘图表。
内容的提问来源于stack exchange,提问作者akd
相关产品推荐
相关产品推荐

