javascriptjqueryhighchartspivotdynamic-columns

How to create stacked column chart using highchart.js with dynamic values


Table

: Array(4) 0 : {MonthsName: 'April', AUTOLIV: 0, Continental: 0, Herman miller: 0, REL: 0, …} 1 : {MonthsName: 'July', AUTOLIV: 0, Continental: 4, Herman miller: 0, REL: 0, …} 2 : {MonthsName: 'June', AUTOLIV: 1, Continental: 0, Herman miller: 0, REL: 0, …} 3 : {MonthsName: 'May', AUTOLIV: 1, Continental: 0, Herman miller: 1, REL: 1, …} length : 4 [[Prototype]] : Array(0) [[Prototype]] : Object

This is my result getting from db after doing PIVOT function

Month Name should come as x-axis and Other column should come as stacked values with its count.

Thanks in Advance.


Solution

  • You need to map your data to the series structure required by Highcharts. You can do that for example in this way:

    const data = [{
        MonthsName: 'April',
        AUTOLIV: 0,
        Continental: 0,
        'Herman miller': 0,
        REL: 0
      },
      ...
    ];
    
    const xKey = 'MonthsName';
    const series = {};
    const chartSeries = [];
    
    data.forEach((dataObj, index) => {
      for (let key in dataObj) {
        if (key !== xKey) {
          if (index === 0) {
            series[key] = {
              name: key,
              data: []
            };
          }
          series[key].data.push({
            name: dataObj[xKey],
            y: dataObj[key]
          });
        }
      }
    });
    
    for (let key in series) {
      chartSeries.push(series[key]);
    }
    
    Highcharts.chart('container', {
      chart: {
        type: 'column'
      },
      xAxis: {
        type: 'category'
      },
      plotOptions: {
        column: {
          stacking: 'normal'
        }
      },
      series: chartSeries
    });
    

    Live demo: https://jsfiddle.net/BlackLabel/esj6hun5/

    API Reference: https://api.highcharts.com/highcharts/series.column.data