Highcharts下钻矩形树图如何仅展示当前子系列对应colorAxis图例
Highcharts 下钻矩形树图动态控制 colorAxis 图例的实现方案
核心实现思路
不需要依赖全局开启图例后的筛选逻辑,直接利用 Highcharts 对单个 colorAxis 的独立显隐控制能力,结合 drilldown、drillupall 交互事件动态切换对应图例的展示状态,即可实现主层级无图例、子层级仅展示当前激活系列对应图例的效果。
具体配置调整步骤
- 关闭全局默认图例渲染,避免所有 colorAxis 自动挂载图例:
legend: { enabled: false // 替换你当前全局开启的配置 }
- 为每个 colorAxis 单独设置初始的图例展示状态,全部初始化为不展示,核心通过 showInLegend 属性控制单个 colorAxis 的图例显隐:
colorAxis: [ // 主层级对应的colorAxis { showInLegend: false, // 保留你原有的主层级配色规则 }, // 每个下钻子层级对应的独立colorAxis { showInLegend: false, // 对应子层级的配色规则 }, { showInLegend: false, // 对应其余子层级的配色规则 } ]
- 给每个子层级的系列添加自定义标识,标记其绑定的 colorAxis 索引,方便交互时精准匹配:
series: [ // 主层级系列原有配置 { type: 'treemap', data: [] }, // 子层级系列配置 { type: 'treemap', customColorAxisIndex: 1, // 与colorAxis数组的索引一一对应 data: [] } ]
- 绑定图表交互事件,动态切换图例显隐:
chart: { events: { // 下钻到子层级时触发 drilldown: function (e) { // 先隐藏所有已激活的图例 this.colorAxis.forEach(axis => axis.update({showInLegend: false}, false)); // 找到当前下钻子系列绑定的目标colorAxis,开启其图例展示 const targetAxisIndex = e.point.series.options.customColorAxisIndex; this.colorAxis[targetAxisIndex].update({showInLegend: true}); }, // 返回顶层时触发 drillupall: function () { // 回到主层级时隐藏所有图例 this.colorAxis.forEach(axis => axis.update({showInLegend: false})); } } }
补充适配说明
- 如果动态修改显隐后图例没有即时刷新,在所有配置更新完成后追加调用
this.legend.render()手动触发图例重绘即可 - 可根据需要调整单个 colorAxis 图例的位置、样式,无需全局配置影响其他图例
内容的提问来源于stack exchange,提问作者vegaelce
相关产品推荐
相关产品推荐

