I have a D3 force directed graph and each node displays a label. This label can vary in length from a single line of text to multiple lines of text. I have successfully created a multiline label for the nodes by referring to this post. However, I would like to vertically center the label over the node. I have not been able to reassign the label position to vertical center in a way that is effective across all label types (e.g. one line labels, two line labels, etc).
Essentially, I am unsure how to center the label as a whole while maintaining separation between each line of text in the label. Any assistance would be appreciated.
var node = svg.selectAll('.node')
.data(force.nodes())
.enter().append('circle')
.attr('class', 'node')
.attr('r', width * 0.01)
.style('fill', function(d) {return color(d.group); })
var maxLength = 20;
var separation = 12;
var textX = 0;
var text = svg.selectAll(".text")
.data(nodes)
.enter().append("text")
.style("text-anchor", "middle")
.each(function (d) {
var lines = wordwrap2(d.name, maxLength).split('\n');
for (var i = 0; i < lines.length; i++) {
d3.select(this)
.append("tspan")
.attr("dy", separation)
.attr("x", textX)
.text(lines[i]);
}});
function wordwrap2( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{0,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
};