简体   繁体   中英

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

as a JSFiddle here:

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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