3

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!

seth127
  • 2,594
  • 5
  • 30
  • 43
  • 1
    is this you are looking for? https://stackoverflow.com/questions/11252753/rotate-x-axis-text-in-d3 – mrdeadsven May 24 '18 at 11:19
  • `rotate` as a attribute of `` is different from the `rotate` in the `transform` attribute. Have a look at the [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text): *"This attribute set the orientation of **each** individual glyph."*. – Gerardo Furtado May 24 '18 at 11:28

1 Answers1

6

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 + ')')
cullimorer
  • 755
  • 1
  • 5
  • 23
  • 1
    Thank you. I'm not 100% sure, but that appears to be rotating them relative to the origin. I'd like to rotate them relative to the `attr("x", ..)` and `attr("y", ..)` that I give them each. I can attach a screen shot if necessary. – seth127 May 24 '18 at 12:19
  • Yea please, could you attach a screenshot with as much detail as you can. – cullimorer May 24 '18 at 12:33
  • I think I understand now what you mean. I've updated the answer to include what I think you want. – cullimorer May 24 '18 at 13:01
  • I can't get your idea to work in practice @ArnaudStephan, see http://plnkr.co/edit/9pxJLz?p=preview – cullimorer May 24 '18 at 13:10
  • I'm not sure I understand what you want, because your Plunker seems fine to me. – Arnaud Stephan May 24 '18 at 13:34
  • @ArnaudStephan if you take another look at my plnkr then you can see how adding what I said into the transform function gets the desired result. – cullimorer May 24 '18 at 13:35
  • @GerardoFurtado Indeed it is, my mistake. I deleted my comment. – Arnaud Stephan May 24 '18 at 14:17