在 Force 布局中为 d3 节点添加文本标签

Add text label to d3 node in Force layout

这是我的代码,你也可以在 JsFiddle 上找到完整的代码。 我想在每个节点上都有标签,但我做不到。 顺便说一句,标签可以嵌入到console.

中的圆圈中
var nodes = svg.selectAll("circle")
                    .data(dataset.nodes)
                    .enter()
                    .append("circle")
                    .attr("r", 10)
                    .style("fill", function(d, i){
                        return colors(i);
                    })
                    .call(force.drag);
    var label = nodes.append("svg:text")
                    .text(function (d) { return d.name; })
                    .style("text-anchor", "middle")
                    .style("fill", "#555")
                    .style("font-family", "Arial")
                    .style("font-size", 12);



    force.on("tick", function(){
        edges.attr("x1", function(d){ return d.source.x; })
             .attr("y1", function(d){ return d.source.y; })
             .attr("x2", function(d){ return d.target.x; })
             .attr("y2", function(d){ return d.target.y; });
        nodes.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; });


    });

现在,您正在将 text 元素附加到 circle 元素,这根本行不通。

当你写...

var label = nodes.append("svg:text")

您正在将文本附加到 nodes选择。但是,您必须记住 nodes 是什么:

var nodes = svg.selectAll("circle")
    .data(dataset.nodes)
    .enter()
    .append("circle")

因此,您将文本附加到圆圈中,但这是行不通的。它们会在您检查页面时显示(如 <circle><text></text></circle>),但实际上不会在 SVG 中显示任何内容。

解决方法:改成:

即可
var label = svg.selectAll(null)
    .data(dataset.nodes)
    .enter()
    .append("text")
    .text(function (d) { return d.name; })
    .style("text-anchor", "middle")
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

这里是fiddle:https://jsfiddle.net/gerardofurtado/7pvhxfzg/1/