seth127
seth127

Reputation: 2724

d3.js rotate text in svg

I'm fairly new to d3 but this seems like a fairly simple question that I can't find the answer to. Maybe I'm just missing something fundamental. Anyway, any help is much appreciated.

I've create circles in my svg and I want to label them with text, which I have accomplished, but the text overlaps, so I want to rotate the text 45 degrees (technically 315 degrees). Here is a snippet of my code to attempt this:

        var texts = svg.selectAll("text")
            .data(data)
            .enter()
            .append("text")
            .attr ("x",function(d, i) { return (i * 30) + 50;})
            .attr ("y",function(d) { return 250 - (d.some_var * 50);})
            .attr("rotate", 315)
            .text(function(d){ return d.name; });

Weirdly though, this rotates each letter in the word instead of rotating the whole word. Screenshot is attached.

enter image description here

What am I missing here? Thanks for any direction!

Upvotes: 3

Views: 2065

Answers (1)

cullimorer
cullimorer

Reputation: 755

At the moment you are rotating each text element:

.attr("rotate", 315)

Instead you need to transform the whole text element, so replace the the rotate with the following:

.attr('transform', 'rotate(45)')

You will need to tweak the values for your needs but it should do the trick.

You can also pass in the x/y coordinates straight into the rotate function to maintain it's placement, i.e.

.attr('transform', 'rotate(45 ' + xValue + ' ' + yValue + ')')

Upvotes: 6

Related Questions