Search code examples
reactjshighchartsstacked-chart

How to customize each column in Highcharts stacked column


Hi I need to customize each column in highcharts stacked column

like this image

I this implementation i have given like this

{
categories:["6-7","7-8"]
series: [{
        name: 'pass',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Fail',
        data: [2, 2, 3, 2, 1]
    }]
}

But now I need to change this implementation and i have to customize each column and add categories how do i achieve this i'm having a array like this

[{"pass":2,"fail":3,"category":"6-7","percentage":"20%"}
{"pass":5,"fail":0,"category":"7-8","percentage":"10%"}]

i wanted like this

|percentage|
------------
|  pass    |
|  fail    |
-----------------
  category

Solution

  • You need to preprocess your data to create series structure required by Highcharts. The 'category' label is achievable by using name property and 'percentage' by stack-labels formatter:

    var data = [{
        "pass": 2,
        "fail": 3,
        "category": "6-7",
        "percentage": "20%"
    }, {
        "pass": 5,
        "fail": 0,
        "category": "7-8",
        "percentage": "10%"
    }];
    
    var series = [{
        name: 'Pass',
        data: []
    }, {
        name: 'Fail',
        data: []
    }];
    
    data.forEach(function(dataObj) {
        series[0].data.push({
            y: dataObj.pass,
            name: dataObj.category,
            percentage: dataObj.percentage
        });
        series[1].data.push({
            y: dataObj.fail,
            name: dataObj.category
        });
    });
    
    Highcharts.chart('container', {
        chart: {
            type: 'column'
        },
        xAxis: {
            type: 'category'
        },
        yAxis: {
            stackLabels: {
                enabled: true,
                formatter: function() {
                    return this.axis.series[0].options.data[this.x].percentage;
                }
            }
        },
        plotOptions: {
            column: {
                stacking: 'normal'
            }
        },
        series: series
    });
    

    Live demo: http://jsfiddle.net/BlackLabel/nfbq2soe/

    API Reference: https://api.highcharts.com/highcharts/yAxis.stackLabels.formatter