Chartjs-Stacked Group Bar from Chart.js : Can I give each stack group a unique color?

0👍

You can do it simply by using the same colour array for each dataset, e.g.:

var ctx = document.getElementById('myChart2').getContext('2d'),
  dateLabelArray = ['2019-06-10', '2019-06-09', '2019-06-08', '2019-06-07'],
  amArray = [2, 1, 2, 1],
  pmArray = [2, 1, 2, 1],
  colours = ['green', 'red', 'blue', 'yellow'],
  myChart2 = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: dateLabelArray,
      datasets: [{
          label: 'AM',
          backgroundColor: colours,
          borderColor: colours,
          borderWidth: 1.5,
          stack: 'Stack 0',
          data: amArray
        },
        {
          label: 'PM',
          backgroundColor: colours,
          borderColor: colours,
          borderWidth: 1.5,
          stack: 'Stack 1',
          data: pmArray
        }
      ]
    },
    options: {
      scales: {
        xAxes: [{
          stacked: true
        }],
        yAxes: [{
          stacked: true,
          ticks: {
            beginAtZero: true,
            callback: function(label, index, labels) {
              switch (label) {
                case 0:
                  return 'Challenged';
                case 1:
                  return 'Positive';
                case 2:
                  return 'Neutral';
              }
            }
          }
        }]
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="myChart2"></canvas>

Leave a comment