17

I'm using the Grouped Bar Chart(http://bl.ocks.org/mbostock/3887051), but the text of the x-axis is very long, as shown in attached picture. How to rotate the text? Thank you. enter image description here

VividD
  • 10,456
  • 6
  • 64
  • 111
Linlin
  • 2,127
  • 5
  • 20
  • 25

3 Answers3

25

A reasonable solution can be found here

The result looks like this:

enter image description here

Make sure you fully understand this portion of code:

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")  
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", "rotate(-65)");

-65 is the angle the label text is rotated, in degrees.

Also, you should increase margin at the bottom, so that the rotated text doesn't get clipped.

WARNING: Rotated text is inevitably rendered by browsers at the end (D3 just creates appropriate svg that is interpreted by browsers), and they do a lousy job rendering rotated text (as opposed to lets say advanced drawing or diagramming software).

Also, related StackOverflow questions:

rotate-x-axis-text-in-d3

how-to-rotate-x-axis-text-in-dimple-js

Community
  • 1
  • 1
VividD
  • 10,456
  • 6
  • 64
  • 111
6

You might want to consider using D3FC, which has a drop-in replacement for the D3 axis component that supports this feature.

D3FC has an adapter component that will automatically rotate axis labels if they collide:

const axis = fc.axisLabelRotate(fc.axisOrdinalBottom(foodScale));

Here it is in action:

enter image description here

Full disclosure - I am a maintainer and contributor to the D3FC library!

ColinE
  • 68,894
  • 15
  • 164
  • 232
  • any guides on how to make this work when brushing and zooming? Something like`xAxis.transition().duration(1000).call(fc.axisLabelRotate(fc.axisBottom(x)))` doesn't work and I am having difficulty understanding `decorate`. – Rahul Jun 21 '22 at 14:49
5

Use SVG transform attribute rotate,

This transform definition specifies a rotation by a degrees about a given point

Try this code :

DEMO

 svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("id", "x")
        .attr("transform", "translate(0," + (h) + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", function (d) {
        return "rotate(-30)";
    });
Manoj
  • 1,860
  • 1
  • 13
  • 25
  • Just a note: passing a function into the final `attr()` call isn't required, since the string doesn't depend on the datapoint. – APerson Jan 03 '17 at 02:32