在Hobbelt的“组/捆绑节点” D3强制布局示例中向节点添加标签吗?

Tim*_*Tim 2 javascript svg label d3.js force-layout

我改编了Ger Hobbelt关于组/捆绑节点的出色示例 https://gist.github.com/GerHobbelt/3071239

作为此处的JSFiddle:

https://jsfiddle.net/NovasTaylor/tco2fkad/

显示屏同时展示了可折叠的节点和区域(船体)。

我无法进行的一项调整是如何向扩展节点添加标签。我已使用类似于以下代码的代码成功将标签添加到其他强制网络图中的节点:

nodes.append("text")
     .attr("class", "nodetext")
     .attr("dx", 12)
     .attr("dy", ".35em")
     .text(function(d) {
         // d.name is a label for the node, present in the JSON source
         return d.name;
     });  
Run Code Online (Sandbox Code Playgroud)

有没有足够熟悉Ger的榜样的人来指导我正确的方向?

Mar*_*ark 5

上输入的,而不是追加,circle追加gcircletext。然后重构一下,以固定g而不是的移动circle。最后,.text()仅在节点具有名称(即是叶子)的情况下追加写出:

node = nodeg.selectAll("g.node").data(net.nodes, nodeid);
node.exit().remove();
var onEnter = node.enter();   
var g = onEnter
  .append("g")
  .attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
  .attr("transform", function(d) { 
      return "translate(" + d.x + "," + d.y + ")"; 
  });   
g.append("circle")
  // if (d.size) -- d.size > 0 when d is a group node.      
  .attr("r", function(d) { return d.size ? d.size + dr : dr+1; })
  .style("fill", function(d) { return fill(d.group); })
  .on("click", function(d) {
    expand[d.group] = !expand[d.group];
    init();
  });  
g.append("text")
  .attr("fill","black")
  .text(function(d,i){
    if (d['name']){          
      return d['name'];
    }
});
Run Code Online (Sandbox Code Playgroud)

并重构刻度以使用g而不是圆圈:

 node.attr("transform", function(d) { 
   return "translate(" + d.x + "," + d.y + ")"; 
 });
Run Code Online (Sandbox Code Playgroud)

更新小提琴