Search code examples
highchartsbar-chartaxes

Can I use two "categories" arrays in a stacked bar chart?


I'm using a stacked percentage bar chart in Highcharts. (This jsfiddle is similar to our chart, derived from an example on the Highcharts site.)

What I'd like to do is add another set of "category" labels on the right side of the chart. Where the left side has labels for each bar, I'd like to show an average on the right. (Calculating this average and putting it in the Highcharts configuration data is done on the server side; in the fiddle I've just hard-coded some dummy values.)

I've tried using multiple x-axis configurations, with the averages categories marked opposite: true to put them on the right side. I can see that adding this is changing the chart, especially if I don't put them on opposite, but the labels don't actually show in any configuration I've tried. Is this possible? If so, what do I need to do that I'm not yet doing?

This is the configuration in the jsFiddle example:

$('#container').highcharts({
    chart: {
        type: 'bar'
    },
    title: {
        text: 'Stacked bar chart'
    },
    xAxis: [{
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    }, {
        title: 'Avg.',
        categories: [3.0, 3.3, 3.6, 2.6, 3.0],
      opposite: true
    }],
    yAxis: {
        min: 0,
        title: {
            text: 'Percent fruit consumption'
        }
    },
    plotOptions: {
        series: {
            stacking: 'percent'
        }
    },
    series: [{
        name: 'John',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Jane',
        data: [2, 2, 3, 2, 1]
    }, {
        name: 'Joe',
        data: [3, 4, 4, 2, 5]
    }]
});

Solution

  • You have the correct axis set up, but currently the chart doesn't know what to do with the second axis.

    Highcharts requires that an axis has either a data series attached to it, or that it is linked to another axis that does, in order to display it.

    If you add a linkedTo property, it will work as required:

    xAxis: [{
        categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
    }, {
        linkedTo: 0, // <-- now the chart will show it, as long as axis 0 is able to be shown
        title: 'Avg.',
        categories: [3.0, 3.3, 3.6, 2.6, 3.0],
        opposite: true
    }]
    

    Updated fiddle: