Chartjs-How to display different datasets from different ajax calls in the same ChartJS?

0👍

Let’s suppose you fetched your data and have multiple statistics/arrays containing the data for each month.

You can compute a lookup that maps the month to the values of the different statistics.

The labels are simply the keys, although you’d probably want to sort them based on the date. The datasets can easily be computed by mapping the labels.

var lkp = [stat1, stat2].flat().reduce((acc, cur) => {
  const {
    month,
    value
  } = cur;
  acc[month] = acc[month] || [];
  acc[month].push(value);
  return acc;
}, {});

//{'June 2020': [0, 10], ...}

var labels = Object.keys(lkp).sort((a, b) => (Date.parse(a) % (1000 * 60 * 60 * 24 * 365)) - (Date.parse(b) % (1000 * 60 * 60 * 24 * 365)))
// ['June 2020', 'May 2020']

var colors = ['red', 'green'];

var datasets = [0, 1].map((index) => {
  const data = labels.map(label => lkp[label][index]);
  return {
    data,
    label: `Statistic ${index}`,
    backgroundColor: colors[index],
  }
});

var options = {
  type: 'bar',
  data: {
    labels,
    datasets,
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chart').getContext('2d');

try {
  new Chart(ctx, options);
} catch (e) {
  //catch co error
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<script>
var stat1 = [{"month":"June 2020","value":0},{"month":"May 2020","value":0},{"month":"April 2020","value":0},{"month":"March 2020","value":0},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":143},{"month":"November 2019","value":111},{"month":"October 2019","value":103},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}]
var stat2 = [{"month":"June 2020","value":10},{"month":"May 2020","value":25},{"month":"April 2020","value":75},{"month":"March 2020","value":80},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":23},{"month":"November 2019","value":123},{"month":"October 2019","value":50},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}];

</script>
<canvas id="chart" width="600" height="400"></canvas>

0👍

I have finally succeeded, based on Martin M.’s idea.
Here is my code (maybe it can help someone who has the same issue).
It works perfectly.

var graph = setChart();
updateChart();

function setChart() {
    $.when(getData1()).done(function (stats) {

        stats = JSON.parse(stats);

        var data = [], labels = [];

        stats.forEach(function (s) {
            labels.push(s.month);
            data.push(s.value);
        });

        var ctx = document.getElementById('graph').getContext('2d');

        return graph = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'data 1',
                        data: data,
                        backgroundColor: '#00c0ef',
                    }],
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            }
        });
    });
}


function updateChart() {
    $.when(setChart()).done(function () {

// I've repeated the following block for data 3 and 4 (still inside updateChart())
        $.when(getData2()).done(function (stats) {

            stats = JSON.parse(stats);
            var data = [];

            stats.forEach(function (s) {
                data.push(s.value);
            });

            var dataset = {};
            dataset.label = "data 2";
            dataset.backgroundColor = '#061834';
            dataset.data = data;

            graph.data.datasets.push(dataset);
            graph.update();
        })
    })
}

Thank you all for your help !

Leave a comment