Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center 90º rotated text in SVG

Tags:

svg

d3.js

Working with D3, I want to have a Y axis label which is rotated -90º and centered on the Y axis. I thought this 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 render a <text> element to the bottom left of the chart, then center the text relative to that bottom left point. The width does not change and thus instead of being centered it runs off the bottom left hand corner of the svg.

I had guessed that if the width was equal to the height of the chart, then the text within it would become vertically centered. That doesn't seem to be the case -OR- there is some magic display:block type property I need to set in SVG in order for width to work on the <text> element.

How should this be done?


Based on the responses, I went with a javascript route and modified the above line to be (height/2)...

.attr('transform', 'translate(-' + yAxisSpacing + ',' + height / 2 + ') rotate(-90)')
like image 323
T. Stone Avatar asked Aug 27 '12 19:08

T. Stone


1 Answers

A width attribute has no effect on <text> in SVG 1.1. The text will be centered (due to text-anchor=middle) around the x,y position defined by the x and y attributes (they default to 0 if you don't specify them). After that the transform attribute is applied.

like image 125
Erik Dahlström Avatar answered Oct 02 '22 13:10

Erik Dahlström