Display text in D3

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

I am trying to get text to display next to each node in the graph. There is a key in the JSON data with a name namethat contains the character name of 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 just changed .textto try to display the text. Can anyone explain how I can display text? Thanks in advance.

+5
source share
1 answer

SVG <circle> , , .text. , SVG <g>. <circle> <text>.

:

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

, <g> .

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

http://jsfiddle.net/vrWDc/19/. - , .

+11

All Articles