Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

javascript - Add text label to d3 node in Force layout

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


    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...