Search code examples
javascriptchartshighchartsstacked

Add new series to the top of a highcharts stacked column chart


I'm trying to control the order in which new (after first render) series are added to a stacked column chart in Highcharts. Right now, if you simply use addSeries, the newly added series is added to the bottom of the stack. Here's a simplified version of what I'm doing

var chart = new Highcharts.Chart({

    chart: {
        type: 'column',
        renderTo: 'container'
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar']
    },

    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },

    series: [{
        name: 'base',
        data: [10, 20, 30]
    }, {
        name: 'sec',
        data: [30, 20, 10]
    }]
});

var i = 0;
$('#add').on('click', function (e) {
    chart.addSeries({
        data: [32, 43, 42],
        name: ++i,
        index: 0 //??????
    });
});

Here's a fiddle of this: http://jsfiddle.net/6bCBf/

Any one can think of a way to reverse/control where Highcharts inserts the new series?

I've tried setting the index of the new series to 0, but that does nothing. Setting it to -1 adds the new series to the bottom of the array, but then that 'stacking' does not work properly


Solution

  • You can set index and zIndex to keep order between layers, then add serie with appropriate parameters.

    Example: http://jsfiddle.net/6bCBf/5/

    var chart = new Highcharts.Chart({
    
        chart: {
            type: 'column',
            renderTo: 'container'
        },
    
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar']
        },
    
        plotOptions: {
            series: {
                stacking: 'normal'
             }
         },    
    
        series: [
            {
                name: 'base',
                data: [10, 20, 30],
                index:2,
                zIndex:10
            },
            {
                name: 'sec',
                data: [30, 20, 10],
                index:1,
                zIndex:9
            }
        ]
    },function(chart){
    
    
    
        $('#add').on('click', function (e) {
    
            chart.addSeries({
                data: [32, 43, 42],
                index: 0,
                zIndex:1
            });
        });
    
    
    });