Add text label to d3 node in Force layout

坚强是说给别人听的谎言 提交于 2019-12-17 07:41:25

问题


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


    });

回答1:


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/



来源:https://stackoverflow.com/questions/37640027/add-text-label-to-d3-node-in-force-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!