sirwebber
sirwebber

Reputation: 157

Adding labels to D3 force graph

I am attempting to modify this D3 example to add labels to the nodes. Here is a fiddle replicating the code from the example.

I believe I need to edit the start() function since it is what is being called every time the node and edge data updates:

function start() {
  link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
  link.enter().insert("line", ".node").attr("class", "link");
  link.exit().remove();

  node = node.data(force.nodes(), function(d) { return d.id;});
  node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8).call(force.drag);
  node.exit().remove();

  force.start();
}

I've tried re-writing the node part of the start() function to append a group element (as suggested by this stackoverflow answer, and then add both the text and circle nodes to the group:

  node = node.data(force.nodes(), function(d) { return d.id;});

  // Append a group element
  node.enter().append("g");

  // Append text to the group element
  node.append("text").text(function(d) { return d.id ;});

  // Append circle to the group element
  node.enter().append("circle")
    .attr("class", function(d) { return "node " + d.id; })
    .attr("r", 8);

  // Transform the group to proper location
  node.attr("transform", function(d) {
    return 'translate(' + [d.x, d.y] + ')';
  });

  node.exit().remove();

The text node is being added correctly, but the groups are not translating to the correct locations in the figure.

I've updated the fiddle to show my current (non-working) approach.

Upvotes: 3

Views: 157

Answers (1)

Stacey Burns
Stacey Burns

Reputation: 1092

In your tick function, if you translate the node instead of the group I believe it works as you would expect:

function tick() {

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


  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; });
}

fiddle: http://jsfiddle.net/7br2t162/

Upvotes: 1

Related Questions