简体   繁体   English

在 Hobbelt 的“Group/Bundle Nodes”D3 强制布局示例中为节点添加标签?

[英]Add labels to nodes in Hobbelt's “Group/Bundle Nodes” D3 force layout example?

I adapted Ger Hobbelt's excellent example of group/bundle nodes https://gist.github.com/GerHobbelt/3071239我改编了 Ger Hobbelt 的组/捆绑节点的优秀示例https://gist.github.com/GerHobbelt/3071239

as a JSFiddle here:作为这里的 JSFiddle:

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

The display demonstrates both collapsible nodes and regions (hulls).显示展示了可折叠节点和区域(外壳)。

The one tweak that eludes me is how to add labels to expanded nodes.我没有想到的一个调整是如何向扩展节点添加标签。 I have successfully added labels to nodes in my other force network diagrams using code similar to:我已经使用类似于以下内容的代码成功地为我的其他力网络图中的节点添加了标签:

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;
     });  

Is anyone familiar enough with Ger's example to guide me in the right direction?有没有人足够熟悉 Ger 的例子来指导我朝着正确的方向前进?

On enter, instead of appending circle append a g with a circle and a text .在输入时,不是附加circle而是附加带有circletextg Then re-factor a bit to fix the movement of the g instead of the circle .然后重新考虑一下以修复g而不是circle的运动。 Finally, append write out the .text() only if the node has a name (meaning it's a leaf):最后,仅当节点具有名称(意味着它是叶子)时才追加写出.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'];
    }
});

And refactored tick to use g instead of circle:并重构刻度线以使用g而不是 circle:

 node.attr("transform", function(d) { 
   return "translate(" + d.x + "," + d.y + ")"; 
 });

Updated fiddle .更新了小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM