Igor
Igor

Reputation: 139

How to sort the items within each stacking column?

How to sort the items within each stacking column? Asc or desc.

enter image description here

Upvotes: 3

Views: 4444

Answers (3)

Serkan Dede
Serkan Dede

Reputation: 1

You may use the script below to sort the Stacked Chart Bars by category name.

var sortData = function(chartSource) {
    var series = chartSource.series;
    var axis = chartSource.xAxis[0];
    var categories = [];

    if($.isArray(series)) {
        var ser = 
          $.grep(series, function(ser, seriesIndex) 
          {
              return ser.visible;
          })[0];

        $.each(ser.data, 
            function(dataIndex, datum) 
          {
            console.log(datum.category + ':' + datum.stackTotal);
            var obj = {
                name: datum.category,
                index: dataIndex,
                stackTotal: datum.stackTotal
            }
            categories.push(obj);
            }
          );
    }

    categories.sort(function(a, b) {
        var aName = a.name.toLowerCase();
        var bName = b.name.toLowerCase();
        var aTotal = a.stackTotal;
        var bTotal = b.stackTotal;
        //if(aTotal === bTotal) {
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        //} else {
        //    return ((aTotal > bTotal) ? -1 : ((aTotal < bTotal) ? 1 : 0));
        //}
    });

    var mappedIndex = $.map(categories, function(category, index) {
        return category.index;
    });

    categories = $.map(categories, function(category, index) {
        return category.name;
    });

    console.log(categories);
    console.log(mappedIndex);
    axis.setCategories(categories);

    var newDataArray = [];

    $.each(series, function(seriesIndex, ser) {
        newDataArray = [];
        var data = $.map(mappedIndex, function(mappedIndex2, origIndex) {
            var ydata = ser.data[mappedIndex2];
            if(ydata.y!=null){
                var y = ydata.y
                newDataArray.push(y);
                return y;
            }
            else
            { 
                newDataArray.push(null);
                return null;
            }

        });
        ser.setData(newDataArray);
    });


};

Upvotes: 0

Sebastian Bochan
Sebastian Bochan

Reputation: 37588

You can only set global index of serie, but you cannot position each single "stack".

http://api.highcharts.com/highcharts#series.index

Upvotes: 1

wergeld
wergeld

Reputation: 14462

Each series added to a chart is drawn on the chart in the order it was received. To change the order of the chart series you will need to change which series is the first in your list of series items.

That being said - what I think you want to do is to, independently of the series order, sort on each stack by value. I do not think this is possible in HighCharts.

Upvotes: 1

Related Questions