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

杀马特。学长 韩版系。学妹 提交于 2019-12-07 21:40:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28836035/add-labels-to-nodes-in-hobbelts-group-bundle-nodes-d3-force-layout-example

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