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

在D3 Dendrogram中按指定链接数筛选节点并移除后代

树状图聚类节点定位问题求助

给定一个数字(可理解为要切割的链接数或聚类数),例如4,需要找到一条恰好切割对应数量链接的线,定位与这些被切割链接直接相连的节点,并移除这些节点的所有子节点。核心问题是如何正确定位这些目标节点。

示例说明

  • 完整树状图:完整树状图
  • 当数字为2时:红线恰好切割2条链接,对应保留节点00和01,移除其右侧所有子节点:切割2条链接的树状图
  • 当数字为4时:保留4个圈出的节点,移除其余节点:切割4条链接的树状图
  • 当数字为5时:保留5个圈出的节点,移除其余节点:切割5条链接的树状图

我注意到root.descendants()返回的节点包含depth和height信息,但不清楚如何利用这些信息解决问题。若有相关建议或思路请不吝赐教!

完整树状图的代码示例如下:

import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/+esm"

var data = {
  id: "0",
  children: [
    {
      id: "00",
      children: [
        {
          id: "000",
        },
        {
          id: "001",
        },
      ],
      dist: 204.09,
    },
    {
      id: "01",
      children: [
        {
          id: "010",
          children: [
            {
              id: "0100",             
            },
            {
              id: "0101",             
            },
          ],
          dist: 148.59,
        },
        {
          id: "011",        
        },
      ],
      dist: 206.61,
    },
  ],
  dist: 299.78,
}

var width = 350,
  height = 350

var root = d3.hierarchy(data)

const cluster = d3
  .cluster()
  .size([width, height])
  .separation(() => 1)
cluster(root)

const max_dist = d3.max(root.descendants(), (d) => d.data.dist)
const dist_scale = width / max_dist
root.descendants().forEach((node, index) => {
  node.y = (max_dist - (node.data.dist | 0)) * dist_scale
})

var svg = d3
  .select("#full_dendro")
  .append("svg")
  .attr("width", width)
  .attr("height", height)

svg
  .selectAll("path")
  .data(root.links())
  .enter()
  .append("path")
  .attr("d", (d) => {
    return `M${d.source.y},${d.source.x}V${d.target.x}H${d.target.y}`
  })
  .attr("fill", "none")
  .attr("stroke", "black")

svg
  .selectAll("circle")
  .data(root.descendants())
  .enter()
  .append("circle")
  .attr("cx", (d) => d.y)
  .attr("cy", (d) => d.x)
  .attr("r", 2)
  .attr("fill", "black")

内容的提问来源于stack exchange,提问作者hiPeilin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 17:03:18