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

如何将D3.js Force-Directed Diagram调整为树形布局并添加节点文本?

实现树形布局并添加节点文本的修改方案

核心修改思路

要将力导向图转为树形布局,需要替换D3的力导向模拟为树形布局算法,并调整数据结构、元素绘制逻辑,具体实现如下:


完整修改后的代码

// Specify the dimensions of the chart.
const width = 928;
const height = 600;

// Specify the color scale.
const color = d3.scaleOrdinal(d3.schemeCategory10);

// 转换为树形层级数据结构(替代原nodes/links格式)
const treeData = {
  "id": "A",
  "group": 1,
  "children": [
    {
      "id": "B",
      "group": 1,
      "children": [{"id": "D", "group": 1}, {"id": "E", "group": 1}]
    },
    {
      "id": "C",
      "group": 1,
      "children": [{"id": "F", "group": 1}, {"id": "G", "group": 1}]
    }
  ]
};

// 创建树形布局并设置画布大小
const treeLayout = d3.tree().size([height, width - 100]); // 右侧预留文本空间
const root = d3.hierarchy(treeData);
treeLayout(root);

// 获取所有节点和链接数据
const nodes = root.descendants();
const links = root.links();

// Create the SVG container.
const svg = d3.select("svg")
  .attr("width", width)
  .attr("height", height)
  .attr("viewBox", [0, 0, width, height])
  .attr("style", "max-width: 100%; height: auto;");

// 绘制树形链接(使用路径元素)
const link = svg.append("g")
  .attr("stroke", "#999")
  .attr("stroke-opacity", 0.6)
  .selectAll("path")
  .data(links)
  .join("path")
  .attr("d", d3.linkHorizontal()
    .x(d => d.y)
    .y(d => d.x));

// 绘制节点圆圈
const nodeGroup = svg.append("g")
  .attr("stroke", "#fff")
  .attr("stroke-width", 1.5)
  .selectAll("g")
  .data(nodes)
  .join("g")
  .attr("transform", d => `translate(${d.y}, ${d.x})`);

nodeGroup.append("circle")
  .attr("r", 5)
  .attr("fill", d => color(d.data.group));

// 添加节点文本标签
nodeGroup.append("text")
  .attr("x", 8) // 文本在圆圈右侧偏移
  .attr("y", "0.3em")
  .text(d => d.data.id)
  .attr("font-size", 12);

// 添加节点hover提示
nodeGroup.append("title")
  .text(d => d.data.id);

关键修改说明

  1. 数据结构转换
    原nodes/links格式需要转为层级树结构,明确父子嵌套关系,让D3树形布局能直接识别层级逻辑。

  2. 替换力导向模拟
    移除d3.forceSimulation相关代码,改用d3.tree()布局计算每个节点的坐标,通过d3.hierarchy()将树形数据转为布局可处理的层级对象。

  3. 节点与链接绘制调整

    • 链接使用d3.linkHorizontal()生成水平树形路径,替代原直线元素,更贴合树形布局的视觉效果;
    • 节点使用<g>元素组包含圆圈和文本,通过transform直接定位,无需tick函数动态更新位置。
  4. 添加节点文本
    在每个节点的<g>组中添加<text>元素,设置偏移量让文本显示在圆圈右侧,绑定节点的id值作为文本内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:10:56