[Chartjs]-Chart.js – How to push a collection of array into dataset

5👍

You really should provide more information. What have you tried, what failed…
Don’t expect people do your job, wasting their time so you can nap for an hour. StackOverflow is for specific questions and not for letting others do somebody else’s work. And getting data for chart.js is something trivial you can find in any other post about chart.js.

Enough ranting, just letting you know you shouldn’t expect answers in the future for questions like that.

  1. The code you posted in your question is quite different to the one from the codepen link, but this can be due to Narendra Jadhav’s ‘update’. But if confused me enough so I don’t know what you want.
  2. You didn’t stated if you want to update our data so I didn’t implemented updating.
  3. Don’t know the use case of this random randomizeData() does, especially with the fixed length of 7. I changed it but as I don’t know the reason it may be different to your use case.
  4. I don’t know the data format you get from MySQL so I used a possible format. Same as above, could be different to what you want.
  5. Please use an newer version of chart.js and not a year old version. There are no breaking changes, only improvements. Just updating the version eliminated a few bugs, e.g. the strange space between the yAxis and the chart.

Complete code (same as JSBin):

var initialData = [
  {
    'Barcode Sticker Problem':1,
    'Extra':1,
    'Labelling Problem':2,
    'Stock Accuracy':1,
    'Wrong Quality':1
  },{
    'Barcode Sticker Problem':1,
    'Extra':1,
    'Labelling Problem':2,
    'Stock Accuracy':1,
    'Wrong Quality':3
  },
  {
    'Barcode Sticker Problem':2,
    'Extra':2,
    'Labelling Problem':1,
    'Stock Accuracy':2,
    'Wrong Quality':3
  }
]

const colors = [
  'red',
  'blue',
  'green'
]

var barChartData = {
  labels: Object.keys(initialData[0]),
  datasets: []
};

for (var i = 0; i < initialData.length; i++) {
  barChartData.datasets.push(
    {
      label: 'Dataset ' + (i+1),
      backgroundColor: colors[i % colors.length],
      data: Object.values(initialData[i])
    }
  )
}

var barChartOptions = {
  title: {
    display: false,
    text: 'Chart.js Stacked Bar Chart'
  },
  tooltips: {
    mode: 'index',
    intersect: false
  },
  responsive: true,
  scales: {
    xAxes: [{
      stacked: true,
    }],
    yAxes: [{
      stacked: true,
      ticks: {
        precision: 0
      }
    }]
  }
}

var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: barChartOptions
});

document.getElementById('randomizeData').addEventListener('click', function() {
  barChartData.datasets.forEach(dataset=>{
    var newData = []
    for (var i = 0; i < dataset.data.length; i++) {
      newData.push(Math.floor(Math.random()*3)+1)
    }
    dataset.data = newData
  });
  window.myBar.update();
});

Leave a comment