Add text label to d3 node in Force layout

Right now, you are appending the text elements to the circle elements, and that simply won’t work.

When you write…

var label = nodes.append("svg:text")

You’re appending the texts to the nodesselection. However, you have to keep in mind what nodes is:

var nodes = svg.selectAll("circle")
    .data(dataset.nodes)
    .enter()
    .append("circle")

Thus, you are appending the texts to circles, and that doesn’t work. They show up when you inspect the page (as <circle><text></text></circle>), but nothing will actually show up in the SVG.

Solution: just change to:

var label = svg.selectAll(null)
    .data(dataset.nodes)
    .enter()
    .append("text")
    .text(function (d) { return d.name; })
    .style("text-anchor", "middle")
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

Here is the fiddle: https://jsfiddle.net/gerardofurtado/7pvhxfzg/1/

Leave a Comment