user1728853
user1728853

Reputation: 2707

Display text in D3

I am just starting to learn D3 and currently working through understanding this example.

I am trying to get text to display next to each node in the graph. In the JSON data, there is a key named name, which contains the name of a character from Les Misérables. I am trying to display this text next to each node using this code:

var node = svg.selectAll(".node")
        .data(graph.nodes)
        .enter().append("circle")
        .attr("class", "node")
        .attr("r", 5)
        .style("fill", "black")
        .text(function(d) { return d.name;}).style("font-family", "Arial").style("font-size", 12)
        .call(force.drag);

I've basically just altered the .text to try and display text. Can anyone explain how I can get text to display? Thanks in advance.

Upvotes: 7

Views: 9238

Answers (1)

cyon
cyon

Reputation: 9538

The SVG <circle> element will not display any text that you place inside it using the .text function. A way to display the text would be to make the nodes of the graph SVG <g> elements. These can then contain a <circle> and a <text> child elements.

This could look like this :

\\create graph nodes using groups
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g").call(force.drag);

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

node.append("text")
.text(function (d) { return d.name; }); 

You would also need to change the force so that it transforms the group <g> on a tick.

force.on("tick", function () {
...
node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
});

You can see it in action for a small graph at http://jsfiddle.net/vrWDc/19/. This method may not be very efficient when applied to a large graph due to the amount of text that needs to be rendered.

Upvotes: 12

Related Questions