Question

I have a little issue with xCharts that I'm trying to figure out. I want to display a bar chart that shows a number with the day of the week. I've gotten it to do this, however I'm having an issue getting it to show up in the right order. See image below:

enter image description here

As you can see, the days of the week are not in the right order. By reading the documentation on their website I can tell it has something to do with providing the option sortX so I tried a bunch of different things which didn't really work for me.

Below is the code that I use:

var data3 = {
    "xScale": "ordinal",
    "yScale": "linear",
    "type": "bar",
    "main": [{
        "className": ".bstats",
        "data": [{
            "x": "Monday",
            "y": 1
        }, {
            "x": "Tuesday",
            "y": 1
        }, {
            "x": "Wednesday",
            "y": 1
        }, {
            "x": "Thursday",
            "y": 1
        }, {
            "x": "Friday",
            "y": 1
        }, {
            "x": "Saturday",
            "y": 1
        }, {
            "x": "Sunday",
            "y": 1
        }]
    }]
};

var opts = {
    "tickFormatX": function (x) {
        return x.substr(0, 3);
    },
    "sortX": function (a, b) {
        /* Not sure what to do here */
        return 0;
    }
};

var myChart = new xChart('bar', data3, '#day_chart', opts);
var set = [];

$.getJSON('/dashboard/get/busy-days', function (data) {
    $.each(data, function (key, value) {
        set.push({
            x: value.x,
            y: parseInt(value.y, 10)
        });
    });

    myChart.setData({
        "xScale": "ordinal",
        "yScale": "linear",
        "main": [{
            className: ".bstats",
            data: set
        }]
    });
});

The data returned from the JSON request is as follows:

[
   {
      "x":"Monday",
      "y":48
   },
   {
      "x":"Tuesday",
      "y":65
   },
   {
      "x":"Wednesday",
      "y":67
   },
   {
      "x":"Thursday",
      "y":62
   },
   {
      "x":"Friday",
      "y":83
   },
   {
      "x":"Saturday",
      "y":65
   },
   {
      "x":"Sunday",
      "y":56
   }
]

Any help is really appreciated.

Was it helpful?

Solution

Create an object for the days of the week (mydays) should be like:

['Monday':1,'Tuesday':2...]

And on sortX just implement the ordenation.

    "sortX": function (a, b) {
        if (mydays[a.x] > mydays[b.x])
            return 1;
        if (mydays[a.x] < mydays[b.x])
            return -1;
        return 0;
        // or return (!mydays[a.x] && !mydays[b.x]) ? 0 : (mydays[a.x] < mydays[b.x]) ? -1 : 1; 

     }

Links:

http://tenxer.github.io/xcharts/docs/#opt-sortX

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top