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

Shu*_* Wu 6 javascript text label d3.js force-layout

这是我的代码看起来,你也可以在JsFiddle上有完整的代码.我想在每个节点上都有标签,但我不能.顺便说一下,标签可以嵌入控制台的圆圈中.

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


    });
Run Code Online (Sandbox Code Playgroud)

Ger*_*ado 11

现在,您将text元素附加到circle元素,这根本不起作用.

当你写...

var label = nodes.append("svg:text")
Run Code Online (Sandbox Code Playgroud)

您将文本附加到nodes选择中.但是,你必须记住nodes:

var nodes = svg.selectAll("circle")
    .data(dataset.nodes)
    .enter()
    .append("circle")
Run Code Online (Sandbox Code Playgroud)

因此,您将文本附加到圆圈,这不起作用.它们会在您检查页面时显示(as <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);
Run Code Online (Sandbox Code Playgroud)

这是小提琴:https://jsfiddle.net/gerardofurtado/7pvhxfzg/1/