VerletIntegrator
VerletIntegrator

Reputation: 159

Text not showing as label in D3 force layout

I am trying to add label to the nodes in a D3 force layout, but there seems to be some issue with it. All the text just shows up on top of the screen, overlapping on each other. Here is the code snippet:

var link = g.append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(graph.links)
    .enter().append("line");

var node = g.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter().append("circle")
    .attr("r", 2.5)
    .on('click', clicked);

var text = g.append("g")
    .attr("class", "labels")
    .selectAll("text")
    .data(graph.nodes)
    .enter().append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });

Upvotes: 2

Views: 776

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Elements piling up on the top left corner of the SVG (which is the origin) is a symptom of several problems, among them:

  • NaN for the positions
  • Not setting the positions
  • Not translating the element
  • Not including the element in the tickfunction

As you have a force directed chart, the last one is the obvious reason.

Solution: You have to include the text in your ticked function.

function ticked() {
    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; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    text.attr("x", function(d) { return d.x; })
        .attr("y", function(d) { return d.y; });
}

Upvotes: 2

Related Questions