qrius
qrius

Reputation: 631

Highchart aggregate JSON data

Trying to use highcharts in react and my data is in the below format:

data: [{
        country: 'USA',
        color: '#00FF00',
        population: 10
    }, 
    {
        country: 'USA',
        color: '#00FF00',
        population: 2
    },
    {
        country: 'Canada',
        color: '#00FF00',
        population: 13
    }]

What I want to achieve: A column chart with one bar for each unique country(in this example, two bars USA & Canda) and each bar should show the sum of population. That is, USA with 12 and Canada with 13. Also the xAxis names should be USA and Canada.

Is there any option to group by/sum which highchart offers out of the box to solve my case?

When I google 'highchart data aggregation' the first result takes me to the documentation but it doesn't help. Related jsfiddle: https://jsfiddle.net/smj8qwun/1/

Upvotes: 0

Views: 479

Answers (2)

ppotaczek
ppotaczek

Reputation: 39089

You can also convert only country to name, population to y and enable stacking:

series: [{
  type: 'column',
  stacking: true,
  data: [{
      name: 'USA',
      color: '#00FF00',
      y: 10
    },
    {
      name: 'USA',
      color: '#00FF00',
      y: 2
    },
    {
      name: 'Canada',
      color: '#00FF00',
      y: 13
    }
  ]
}]

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4980/

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

Upvotes: 0

Luís Ramalho
Luís Ramalho

Reputation: 10208

You'll have to reduce the data to the format you're looking for, like so:

let o = {
  data: [{
      country: "USA",
      color: "#00FF00",
      population: 10,
    },
    {
      country: "USA",
      color: "#00FF00",
      population: 2,
    },
    {
      country: "Canada",
      color: "#00FF00",
      population: 13,
    },
  ]
}

let formattedData = o.data.reduce((p, c) => {
  let found = p.find((o) => o.country === c.country);
  if (found) {
    found.y += c.population;
  } else {
    let {
      population,
      ...rest
    } = c;
    p.push({ ...rest,
      y: population
    });
  }
  return p;
}, []);

Highcharts.chart('container', {
  chart: {
    type: 'column'
  },

  xAxis: {
    categories: formattedData.map(o => o.country)
  },
  plotOptions: {
    series: {
      // general options for all series
      dataGrouping: {
        enabled: true,
      }
    },
  },

  series: [{
    data: formattedData
  }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>

Upvotes: 1

Related Questions