我正在尝试解决xCharts的一个小问题。我想显示一个条形图,该条形图显示星期几。我已经做到了,但是在以正确的顺序显示它时遇到了问题。见下图:

如您所见,星期几的顺序不正确。通过阅读他们网站上的文档,我可以知道它与提供sortX选项有关,因此我尝试了很多对我而言并不奏效的事情。

以下是我使用的代码:

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
        }]
    });
});

JSON请求返回的数据如下:
[
   {
      "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
   }
]

任何帮助都非常感谢。

最佳答案

创建星期几(mydays)的对象应类似于:



而在sortX上,只需实现整理。

    "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;

     }

链接:

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

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

08-19 14:16