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

2024-03-03

这是我的代码,你也可以有完整的代码JsFiddle https://jsfiddle.net/ShuanWu/7pvhxfzg/。 我想在每个节点上都有标签,但我不能。 顺便说一句,标签可以嵌入到圆圈中console https://i.stack.imgur.com/0IV8Y.jpg.

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 is:

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

因此,您将文本附加到圆圈中,但这不起作用。当您检查页面时它们会出现(如<circle><text></text></circle>),但 SVG 中实际上不会显示任何内容。

Solution: 只需更改为:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Force布局中向d3节点添加文本标签 的相关文章

随机推荐