Chartjs-Stacked bars in Charts.js from a JSON list of objects

1👍

Dataset’s data property is an array of values that will be distributed across the labels (in this case realEnergy value per each lastUpdate). I assume that each dataset should represent particular machine.

Here’s the code to generate datasets and labels based on your JSON data:

const jsonData = JSON.parse(yourJSONData);
const colors = ['yellow', 'green', 'blue']; // purely optional


const machines = jsonData.reduce((uniqueMachines, record) => {
  // find unique machines that will be base to our datasets
  if (!uniqueMachines.find(machine => machine.machineId === record.machine.machineId))
    uniqueMachines.push(record.machine);
  return uniqueMachines;
}, []);

const lastUpdates = jsonData.reduce((uniqueLastUpdates, record) => {
  // get labels for our chart
  if (!uniqueLastUpdates.find(lastUpdate => lastUpdate === record.lastUpdate))
    uniqueLastUpdates.push(record.lastUpdate);
  return uniqueLastUpdates;
}, []);

const datasets = machines.map((machine, index) => {
  const label = machine.name;
  const backgroundColor = colors[index]; // purely optional
  const data = lastUpdates.map(lastUpdate => {
    const valueRecord = jsonData.find(record => record.machine.machineId === machine.machineId && record.lastUpdate === lastUpdate);
    if (!valueRecord) return 0;  // if value record is not defined, return 0;
    return valueRecord.realEnergy;
  });

  return {
    // here we return dataset
    label,
    backgroundColor,
    data,
    stack: 'main' // here we define the stack
  };
});

And here’s the final configuration for the chart:

const myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: lastUpdates,
    datasets
  },
  options: {
    scales: {
      yAxes: [{
        stacked: true
      }]
    }
  }
});

A working example on the JSFiddle: click

Leave a comment