The text-anchor attribute works as expected in the svg element created by D3. However, you need to add text and circle to the regular g element to make sure that text and circle are centered from each other.
To do this, you can change your nodes variable to:
var nodes = svg.append("g") .attr("class", "nodes") .selectAll("circle") .data(dataset) .enter() // Add one g element for each data node here. .append("g") // Position the g element like the circle element used to be. .attr("transform", function(d, i) { // Set dx and dy here so that other elements can use it. d is // expected to be an object here. dx = i * 70 + 50, dy = svg_h / 2; return "translate(" + dx + "," + dy + ")"; });
Note that dataset now a list of objects, so instead of a simple list of strings, you can use dy and dx .
Then replace the circle and text append code as follows:
// Add a circle element to the previously added g element. nodes.append("circle") .attr("class", "node") .attr("r", 20); // Add a text element to the previously added g element. nodes.append("text") .attr("text-anchor", "middle") .text(function(d) { return d.name; });
Now, instead of changing the position of the circle you change the position of the g element, which moves both circle and text .
Here is a JSFiddle showing centered text in circles.
If you want your text to be in a separate g element so that it always appears on top, use the dx and dy values โโset in the first g element for transform text.
var text = svg.append("svg:g").selectAll("g") .data(force.nodes()) .enter().append("svg:g"); text.append("svg:text") .attr("text-anchor", "middle") .text(function(d) { return d.name; }); text.attr("transform", function(d) { return "translate(" + dx + "," + dy + ")"; });
Brant Olsen Aug 08 2018-12-12T00: 00Z
source share