Can't append text to d3.js force layout nodes

柔情痞子 提交于 2019-12-08 04:35:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28789176/cant-append-text-to-d3-js-force-layout-nodes

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