无法将文本附加到d3.js强制布局节点 [英] Can't append text to d3.js force layout nodes

查看:126
本文介绍了无法将文本附加到d3.js强制布局节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OBJECTIVE:向d3强制布局中的每个节点添加文本



BUG:文本附加到对象(我认为,请参阅控制台),但不显示在屏幕上



以下是。




OBJECTIVE: append text to each node in a d3 force layout

BUG: text is appended to the object (I think, see console) but not displayed on screen

Here's the jsfiddle.

node.append("svg:text")
    .text(function (d) { return d.name; }) // note that this works for
    // storing the name as the id, as seen by selecting that element by
    // it's ID in the CSS (see red-stroked node)
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

I'd be so grateful for any thoughts.

解决方案

You can't add svg text to a svg circle. You should first create an svg g object (g stands for group) for each node, and than add a circle and a text for each g element, like in this code:

var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("g");

var circle = node.append("circle")
    .attr("class", "node")
    .attr("id", function (d) { return d.name; })
    .attr("r", 5)
    .style("fill", function (d) {
        return color(d.group);
    });

var label = node.append("svg:text")
    .text(function (d) { return d.name; })
    .style("text-anchor", "middle")
    .style("fill", "#555")
    .style("font-family", "Arial")
    .style("font-size", 12);

Of course, tick function should be updated accordingly: (also css a little bit)

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

Here is jsfiddle.

这篇关于无法将文本附加到d3.js强制布局节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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