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

醉酒当歌 提交于 2019-12-06 10:47:16

On enter, instead of appending circle append a g with a circle and a text. Then re-factor a bit to fix the movement of the g instead of the circle. Finally, append write out the .text() only if the node has a name (meaning it's a leaf):

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:

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

Updated fiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!