Add text label to d3 node in Force layout(在 Force 布局中将文本标签添加到 d3 节点)

本文介绍了在 Force 布局中将文本标签添加到 d3 节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

This is my code look like, you can also have full code on JsFiddle . I want to have labels on every node, but I can't. By the way, labels can be embedded in the circle in the 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; });


    });

解决方案

Right now, you are appending the text elements to the circle elements, and that simply won't work.

When you write...

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

You're appending the texts to the nodesselection. However, you have to keep in mind what nodes is:

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

Thus, you are appending the texts to circles, and that doesn't work. They show up when you inspect the page (as <circle><text></text></circle>), but nothing will actually show up in the SVG.

Solution: just change to:

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

Here is the fiddle: https://jsfiddle.net/gerardofurtado/7pvhxfzg/1/

这篇关于在 Force 布局中将文本标签添加到 d3 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!