Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I position rotated x-axis labels on column chart using nvd3?

I am building a bar chart using nvd3's multiBarChart and need to adjust the position of rotated x-axis labels:

enter image description here

var chart = nv.models.multiBarChart(); ... chart.rotateLabels(-90); 

I would like the column labels to not overlap the chart and be centered under each bar. I could select the labels after plotting the chart and adjust them but is there an easier way?

like image 225
David Tinker Avatar asked Oct 30 '12 10:10

David Tinker


People also ask

How do you rotate the x-axis labels?

Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax.


2 Answers

The best way I have found to handle this is to perform the rotation of the x-axis tick labels yourself. Why? Because NVD3 is not handling the rotation and associated translations properly. Look at your image, and you'll see that the library allows the rotation to translate the labels out from directly under the columns they represent. It also begins to mishandle the axis.tickPadding() values, and so on.

The first thing that you need to do is to ensure that the chart has enough space for the translated labels, like so:

chart.margin({bottom: 60}); 

We can then translate and rotate the labels:

var xTicks = d3.select('.nv-x.nv-axis > g').selectAll('g'); xTicks   .selectAll('text')   .attr('transform', function(d,i,j) { return 'translate (-10, 25) rotate(-90 0,0)' }) ; 

The labels now look like this:

Rotated / translated labels

like image 63
River Avatar answered Oct 13 '22 09:10

River


For multiple graph, your can add "'#' + containerId + ' svg " in the d3.select like below:

//Rotate x-axis label var xTicks = d3.select('#' + containerId + ' svg .nv-x.nv-axis > g').selectAll('g'); xTicks     .selectAll('text')     .attr('transform', function(d,i,j) { return 'translate (-15, 60) rotate(-90 0,0)' }); 

Anyways, Thanks for @River answer.

like image 30
Simon Avatar answered Oct 13 '22 11:10

Simon