在 Force 布局中向 d3 节点添加文本标签 [英] Add text label to d3 node in Force layout

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

问题描述

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

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


    });

推荐答案

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

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

当你写...

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

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

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

因此,您将文本附加到圆圈中,但这是行不通的.当您检查页面时,它们会出现(如 ),但实际上没有任何内容显示在 SVG 中.

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.

解决方案:只需更改为:

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/

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆