无法将文本附加到 d3.js 强制布局节点

Can't append text to d3.js force layout nodes

OBJECTIVE: 将文本附加到 d3 强制布局中的每个节点

BUG:文本附加到对象(我认为,请参阅控制台)但未显示在屏幕上

这是jsfiddle

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

如有任何想法,我将不胜感激。

您不能将 svg 文本添加到 svg 圆圈。您应该首先为每个节点创建一个 svg g 对象(g 代表组),然后为每个 g 元素添加一个圆圈和一个文本,如以下代码所示:

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

当然,tick函数也要相应更新:(也css一点点)

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

这里是jsfiddle.