Placing labels at the center of nodes in d3.js

后端 未结 3 798
北荒
北荒 2020-12-04 23:08

I am starting with d3.js, and am trying to create a row of nodes each of which contains a centered number label.

I am able to produce the desired result visually, bu

3条回答
  •  醉酒成梦
    2020-12-04 23:46

    The best answer came from the asker himself:

    just a further observation: with only .attr("text-anchor", "middle") for each text element, the label is at the middle horizontally but slightly off vertically. I fixed this by adding attr("y", ".3em") (borrowed from examples at d3.js website), which seems to work well even for arbitrary size of node circle. However, what exactly this additional attribute does eludes my understanding. Sure, it does something to the y-coordinate of each text element, but why .3em in particular? It seems almost magical to me...

    Just add .attr("text-anchor", "middle") to each text element.

    Example:

    node.append("text")
        .attr("x", 0)
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .text(function(d) { return d.name; });
    

提交回复
热议问题