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

31,374

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

Share:
31,374
Aditya
Author by

Aditya

Updated on June 10, 2020

Comments

  • Aditya
    Aditya almost 4 years

    I am trying to add text label to nodes in d3 Force Directed Graph, there seems to be an issue. This is my Fiddle:

    enter image description here

    When I add the node name like this:

    node.append("text")
        .attr("class", "word")
        .attr("dy", ".35em")
        .text(function(d) {
            console.log(d.name);
            return d.name;
        });
    

    There's no change but the names are getting logged.

    When i tried using bounding box , the node labels appeared but the nodes are stacked up on the top-left corner of box while the node links are fine.This fiddle is the outcome of that effort i put in. Can anyone tell me what am i doing wrong?

  • Aditya
    Aditya over 10 years
    Pretty much what i wanted, had to edit a bit for the re-size on hover .Thanks a lot.
  • Aaron
    Aaron over 9 years
    I know this post is old, but note that .call(force.drag) should be on gnodes, not node.
  • Pablo Navarro
    Pablo Navarro over 9 years
    Using call(force.drag) on gnodes would allow the user to drag the labels or the circles (everything under the groups), whereas using them in node only allow to drag the circles.
  • RamblerToning
    RamblerToning over 8 years
    Where do I put the exit().remove() call? You need to have that in order to update the graph
  • Pablo Navarro
    Pablo Navarro over 8 years
    Either before or after the force.on('tick', callback) call, probably inside teh drawGraph function on the original fiddle jsfiddle.net/draditya91/RRUzZ