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

2019-05-31 15:36发布

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.

enter image description here

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条回答
时光不老,我们不散
2楼-- · 2019-05-31 16:30

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.

enter image description here

查看更多
登录 后发表回答