Add text label to d3 node in Force directed Graph and resize on hover

旧城冷巷雨未停 提交于 2019-11-27 11:54:37

You are adding a text element inside a circle, that won't work. You can add groups under the svg element and then append the circle and a text in each group:

// Create the groups under svg
var gnodes = svg.selectAll('g.gnode')
  .data(graph.nodes)
  .enter()
  .append('g')
  .classed('gnode', true);

// Add one circle in each group
var node = gnodes.append("circle")
  .attr("class", "node")
  .attr("r", 5)
  .style("fill", function(d) { return color(d.group); })
  .call(force.drag);

// Append the labels to each group
var labels = gnodes.append("text")
  .text(function(d) { return d.name; });

force.on("tick", function() {
  // Update the links
  link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

  // Translate the groups
  gnodes.attr("transform", function(d) { 
    return 'translate(' + [d.x, d.y] + ')'; 
  });    

});

A fork of your fiddle with this strategy is here

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