When working with D3, I want to have a Y axis label that is rotated -90º and centered on the Y axis. I thought it would be a piece of cake, and wrote the following:
// Y Axis Label svg.append('svg:text') .attr('class', 'y label') .attr('text-anchor', 'middle') .attr('y', 0) .attr('width', height) .attr('transform', 'translate(-' + yAxisSpacing + ',' + height + ') rotate(-90)') .text('Y Axis Label')
height in this case is the height of the chart (the vertical area occupied by svg). The above code will display the <text> element in the lower left corner of the chart, and then center the text relative to that lower left point. width does not change, and instead of being centered, it runs through the bottom left corner of svg.
I guessed that if the width was equal to the height chart, then the text inside it would become vertically centered. This doesn't seem to be the case: -OR- there is some kind of magic property like display:block that I need to set in SVG so that width works on the <text> element.
How to do it?
Based on the answers, I went with a javascript route and modified the above line (height / 2) ...
.attr('transform', 'translate(-' + yAxisSpacing + ',' + height / 2 + ') rotate(-90)')
source share