2

OBJECTIVE: append text to each node in a d3 force layout

BUG: text is appended to the object (I think, see console) but not displayed on screen

Here's the jsfiddle.

enter image description here

node.append("svg:text")
    .text(function (d) { return d.name; }) // note that this works for
    // storing the name as the id, as seen by selecting that element by
    // it's ID in the CSS (see red-stroked node)
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

I'd be so grateful for any thoughts.

VividD
  • 10,456
  • 6
  • 64
  • 111
David Mora
  • 23
  • 4
  • Does http://stackoverflow.com/a/18175103/173225 fix it for you? – Colin Young Mar 01 '15 at 02:05
  • 1
    possible duplicate of [Add text label to d3 node in Force directed Graph and resize on hover](http://stackoverflow.com/questions/18164230/add-text-label-to-d3-node-in-force-directed-graph-and-resize-on-hover) – Colin Young Mar 01 '15 at 02:06

1 Answers1

2

You can't add svg text to a svg circle. You should first create an svg g object (g stands for group) for each node, and than add a circle and a text for each g element, like in this code:

var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("g");

var circle = node.append("circle")
    .attr("class", "node")
    .attr("id", function (d) { return d.name; })
    .attr("r", 5)
    .style("fill", function (d) {
        return color(d.group);
    });

var label = node.append("svg:text")
    .text(function (d) { return d.name; })
    .style("text-anchor", "middle")
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

Of course, tick function should be updated accordingly: (also css a little bit)

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

label.attr("x", function (d) {
    return d.x;
})
.attr("y", function (d) {
    return d.y - 10;
});

Here is jsfiddle.

enter image description here

VividD
  • 10,456
  • 6
  • 64
  • 111