Mauro Gentile
Mauro Gentile

Reputation: 1511

d3 rotating text labels

I have text labels that I would like to rotate.

  in_years.selectAll(".xlabel")     
      .data(xTickLabels)
      .enter()
      .append("text")
      .attr("class","xlabel")
      .attr("text-anchor", "end") 
      //.attr("transform", "translate(0,0) rotate(-45)")
      .attr("font-size", "14px")
      .attr("x", (d,i) => xScale(xRange[i]))
      .attr("y", (d,i) => height+15)
      .text(function(d) { console.log(d);return d})
      ;

Wit "transform" line commented I obtain graph 1. Uncommenting the line I obtain graph 2 which does not make sense to me.

Any hint on why this happen and how to solve it? I am using d3 v3 for this enter image description here

enter image description here

Upvotes: 1

Views: 3799

Answers (1)

Weiting Lin
Weiting Lin

Reputation: 206

Why the rotation effect not as your expectation is due to the css property of rotate(). link

According to the rotate function definition in MDN doc:
''The axis of rotation passes through an origin''

So you have to translate each text element's (x,y) in order to let rotation axis is related to its site in the graphic.

// this code, which each text will rotate according to (0,0)
svg.selectAll('text.norotation')
   .data(data)
   .enter()
   .append('text')
   .text((d)=>d)
   .classed('norotation', true)
   .attr('fill', 'black')
   .attr('x', (d,i)=> xScale(i))
   .attr('y', 200)

Modified One

//each text element will rotate according to its position
svg.selectAll('text.rotation')
   .data(data)
   .enter()
   .append('text')
   .text((d)=>d)
   .classed('rotation', true)
   .attr('fill', 'black')
   .attr('transform', (d,i)=>{
        return 'translate( '+xScale(i)+' , '+220+'),'+ 'rotate(45)';})
   .attr('x', 0)
   .attr('y', 0)

Demo on Observalbe:https://beta.observablehq.com/@weitinglin/d3-rotating-text-labels

Upvotes: 3

Related Questions