Search code examples
javascripthighcharts

How can do sum each group and add a bar in the left of each group using highchart


I am using this script to show sum each group and add new bar but it's not working. I have tried many times but not working.please check

let seriesSumArr = [230, 230, 230];
const seriesData = [
    {
        "data": [
            100,
            100,
            100
        ],
        "name": "April"
    },
    {
        "data": [
            50,
            50,
            50
        ],
        "name": "May"
    },
    {
        "data": [
            80,
            80,
            80
        ],
        "name": "Jun"
    }
];

// Calculate the sum for each group
let sums = seriesData.map(series => series.data.reduce((acc, val) => acc + val, 0));
// Add the sum bars to the left side of each group
seriesData.forEach((series, index) => {
    series.data.unshift(seriesSumArr[index]);
});
Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'Monthly Average Rainfall'
    },
    series: seriesData
});

Please check the example which is not working. https://jsfiddle.net/xduq6hsv/5/

Thanks

enter image description here


Solution

  • For example, you can use the forEach() method on an array to sum these points and then simply pass it as another series.

    const seriesData = [{
      name: 'April',
      data: [
        110,
        100,
        120
      ]
    }, {
      name: 'May',
      data: [
        50,
        60
      ]
    }, {
      name: 'Jun',
      data: [
        70,
        80,
        90
      ]
    }];
    
    const sumData = []
    
    seriesData.forEach((_, i) => {
      let sum = 0;
    
      seriesData.forEach((series) => {
        const y = series.data[i];
        if (y) sum += series.data[i]
      })
    
      sumData.push(sum)
    });
    
    Highcharts.chart('container', {
      chart: {
        type: 'column',
      },
      xAxis: {
          categories: seriesData.map(series => series.name),
      },
      series: [{
        name: 'Sum',
        data: sumData,
        color: {
          pattern: {
            color: 'blue',
            path: {
              d: 'M 0 2 L 5 2 M 0 4 L 5 4',
              strokeWidth: 1
            },
            width: 5,
            height: 5,
            opacity: 0.5
          }
        }
      }, ...seriesData]
    });
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
    <script src="https://code.highcharts.com/modules/pattern-fill.js"></script>
    
    <div id="container"></div>

    Demo: https://jsfiddle.net/BlackLabel/u5c28m7s/