2

I am trying to set the start and end for the x axis on a muli barchart. I can render the charts however it is drawing them in the order they are received, according to the dates in the object. How can I reorder the x axis so that is starts with a specific month, like May?

The months I feed d3 are 2 digit (01, 02, 03, etc...)

    var chart = nv.models.multiBarChart();

    chart.xAxis
        .tickFormat(d3.format(',f'));

    chart.yAxis
        .tickFormat(d3.format(',.1f'));

    d3.select('#chart svg')
        .datum(data())
        .transition().duration(500)
        .call(chart)
        ;

    nv.utils.windowResize(chart.update);

    return chart;
});
TechnoTim
  • 3,065
  • 1
  • 23
  • 28
  • 1
    Could you put up a some code you have been working on a [Fiddle](http://jsfiddle.net/) – shabeer90 Aug 29 '14 at 08:25
  • I updated my question with code. The chart gets drawn according to how the key/values are ordered. I was hoping to have them in order and starting with May, rather than just random. – TechnoTim Aug 31 '14 at 18:08

1 Answers1

3

The x-axis for a NVD3 multi-bar chart uses a d3 ordinal scale. The domain (data values) for an ordinal scale are defined as an array of categories; these categories are used by the axis in the order they appear in the array.

As you've discovered, the default behaviour -- if the domain is not set explicitly -- is to add each new category in the order it appears in the data. This is what NVD3 uses.

To sort your x-axis categories, you have two choices:

  1. Sort the data before passing it to the chart. This answer describes how to do that..

  2. Set the x-domain explicitly before running the chart using the NVD3 chart object's .xDomain(array) method.

The array you pass to the xDomain method should have all the x-values you need, in the order you want them. If you know exactly what the categories will be, you could hard code it in your program. A more flexible approach is to generate it from the data, by using array.map to extract the relevant variable from each data object, and then using array.sort to get them in the correct order.

(You could remove duplicates before sorting -- see this Q&A for examples of how -- but this isn't required.)

Community
  • 1
  • 1
AmeliaBR
  • 27,344
  • 6
  • 86
  • 119
  • Thank you. I ended up fixing the dates server side, and now they are in chronological order but I need to have the array start with May. I'll give .xDomain a shot. Thanks! – TechnoTim Sep 01 '14 at 04:13
  • In my case I ended up sorting the dates before passing it to the chart. Not the greatest but it works. Thanks again. – TechnoTim Sep 08 '14 at 18:09