在D3中显示文字

use*_*853 6 d3.js

我刚开始学习D3,目前正在通过理解这个例子.

我试图在图表中的每个节点旁边显示文本.在JSON数据中,有一个名为key的键name,其中包含来自LesMisérables的角色的名称.我试图使用以下代码在每个节点旁边显示此文本:

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);
Run Code Online (Sandbox Code Playgroud)

我基本上只是改变了.text尝试和显示文本.任何人都可以解释我如何才能显示文字?提前致谢.

cyo*_*yon 11

SVG <circle>元素不会显示使用该.text函数放置在其中的任何文本.显示文本的方法是制作图形SVG <g>元素的节点.然后,这些可以包含a <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; }); 
Run Code Online (Sandbox Code Playgroud)

您还需要更改力,以便<g>在刻度线上转换组.

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

您可以在http://jsfiddle.net/vrWDc/19/上查看小图表的实际操作.由于需要渲染的文本量,当应用于大图时,此方法可能效率不高.