Chartjs-How to apply each color to each dataset

1👍

Instead of setting only one dataset, use one for each distinct data(Nepali,…), the down side of this implementation is that you will loss the x label.

var data = [{"0":"Nepali","1":"4","sub":"Nepali","gpa":"4"},{"0":"English","1":"3","sub":"English","gpa":"3"},{"0":"Math","1":"3","sub":"Math","gpa":"3"},{"0":"Science","1":"2","sub":"Science","gpa":"2"},{"0":"Social_Studies","1":"5","sub":"Social_Studies","gpa":"5"}]

window.onload = function() {
  var subData = [];
  var colors = ['red', 'blue', 'green', 'yellow', 'cyan'];

  for (var i in data) {
    subData.push({
      label: data[i].sub,
      backgroundColor: colors[i],
      data: [data[i].gpa]
    });
  }

  var densityCanvas = document.getElementById('student');

  var planetData = {
    labels: [''],
    datasets: subData
  };
  var chartOptions = {
    title: {
      display: true,
      text: 'GPA Mark Figure'
    },
    scales: {
      yAxes: [{
        ticks: {
          fixedStepSize: 1,
          beginAtZero: true
        }
      }],
    },
  };
  var barChart = new Chart(densityCanvas, {
    type: 'bar',
    data: planetData,
    options: chartOptions
  });
}
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js'></script>
<canvas id='student'></canvas>

Leave a comment