How to sort color segments by value within the 100% stacked bars rather than by value across all the stacked bars in Highcharts or ChartJs

0👍

You have to sort this yourself by creating a custom function. Basically, you have to switch to columnrange on initial load and create a new series out of the others. Here is an example:

function resort() {

    function sort(dataL, dataS) {
        return (dataS.y < dataL.y ? 1 : dataS.y > dataL.y ? -1 : 0); //====> this is doing the main sorting
    }
    function label() {
        return (this.point.high - this.point.low).toString();
    }
    function tooltip() {
        return this.key + ': ' + (this.point.high - this.point.low);
    }


    var allSeries = this.options.series,
        colors = this.options.colors,
        firstSeries = allSeries[0],
        stackingMatrix = [];

    Highcharts.each(allSeries, function(series, sIndex) {
        Highcharts.each(series.data, function(point, pIndex) {
            if (sIndex == 0) {
                stackingMatrix[pIndex] = [{
                    series: sIndex,
                    y: point
                }];
            } else {
                stackingMatrix[pIndex].push({
                    series: sIndex,
                    y: point
                });
            }
        });
    });


    var stackData = [];

    Highcharts.each(stackingMatrix, function(stack, index) {
        var stackY = 0;
        stack = stackingMatrix[index].sort(sort);
        Highcharts.each(stack, function(point) {
            stackData.push({
                color: colors[point.series],
                dataLabels: {
                    align: 'center',
                    enabled: true,
                    formatter: label,
                    inside: true,
                    verticalAlign: 'middle'
                },
                low: stackY,
                high: (stackY + point.y),
                name: allSeries[point.series].name,
                x: index
            });
            stackY = (stackY + point.y);
        });
    });

    this.update({
        tooltip: {
            formatter: tooltip
        },
        series: [{
            type: 'columnrange',
            data: stackData
        }, {
            data: []
        }, {
            data: []
        }]
    });

}

and then simply call the resort() function

Highcharts.chart('container', {
    chart: {
        type: 'column',
        events: {
            load: resort
        }
    },
    [...]
});

Working Example: https://jsfiddle.net/mrAhmedkhan/jfh5r6ym/

Leave a comment