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

实现Highcharts桑基图双击节点隐藏其下游所有节点及连线

实现Highcharts桑基图双击节点隐藏其下游所有节点及连线

嗨,我看了你的问题,你现在已经能双击节点隐藏对应的连线,但还没搞定下游节点的隐藏对吧?其实只需要在处理连线的同时,把下游节点的图形也设置为隐藏状态,甚至可以递归处理所有层级的下游节点,确保它们都被隐藏。下面是修改后的完整代码,我标了关键改动的地方:

修改后的JavaScript代码

Highcharts.chart("container", {
  title: {
    text: "Cash flow"
  },
  chart: {
    events: {
      load: function() {
        let chart = this;

        chart.series[0].points.forEach((point) => {
          point.graphic.element.addEventListener("dblclick", function() {
            // 递归函数:隐藏目标节点及其所有下游节点、连线
            const hideDownstream = (node) => {
              // 隐藏当前节点的图形
              if (node.graphic) {
                node.graphic.hide();
              }
              // 隐藏从该节点出发的所有连线
              node.linksFrom.forEach((link) => {
                link.update({ color: 'transparent', weight: 0 }, false);
                // 递归处理连线指向的下游节点
                hideDownstream(link.toNode);
              });
            };

            // 从点击节点的直接下游节点开始处理
            hideDownstream(point.toNode);
            // 刷新图表使修改生效
            chart.redraw();
          });
        });
      }
    }
  },

  accessibility: {
    point: {
      valueDescriptionFormat: "{index}. {point.from} to {point.to}, " + "{point.weight}."
    }
  },
  tooltip: {
    headerFormat: null,
    pointFormat: "{point.fromNode.name} \u2192 {point.toNode.name}: {point.weight:.2f} ",
    nodeFormat: "{point.name}: {point.sum:.2f}"
  },
  series: [{
    keys: ["from", "to", "weight"],
    data: [
      ["Salary", "Income", 5],
      ["Dividend", "Income", 2],
      ["Bonus", "Income", 3],

      ["Income", "Tax", 1],
      ["Income", "Shopping", 3],
      ["Income", "Invest", 6],

      ["Shopping", "Online", 1],
      ["Shopping", "Offline", 2]
    ],
    type: "sankey",
    name: "Sankey demo series"
  }]
});

HTML代码(无需改动)

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/sankey.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
  <div id="container"></div>
</figure>

关键改动说明

  • 新增了递归函数hideDownstream:用来处理单个节点的隐藏,同时遍历该节点的所有下游连线和节点,实现全层级的隐藏
  • 使用node.graphic.hide():直接隐藏节点的可视化元素,这是你之前遗漏的核心步骤
  • 递归调用处理下游:确保不仅隐藏直接子节点,连间接的下游节点(比如如果Online还有子节点的话)也会被一并隐藏
  • 最后调用chart.redraw():让所有修改的样式和隐藏操作立即生效

备注:内容来源于stack exchange,提问作者CaffeinatedCod3r

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:43:10