Chartjs-ChartJS with Dynamic Colors

4👍

You are looking for something like the following:

var chart = new Chart(ctx, {
   type: 'horizontalBar',
   data: {
      labels: [18, 82, 22, 80],
      datasets: [{
         data: [1, 2, 3, 4],
         backgroundColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff'],
         borderColor: ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff']
      }]
   },
   options: {
      scales: {
         xAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      },
      legend: {
         labels: {
            generateLabels: function(chart) {
               var labels = chart.data.labels;
               var dataset = chart.data.datasets[0];
               var legend = labels.map(function(label, index) {
                  return {
                     datasetIndex: 0,
                     text: label,
                     fillStyle: dataset.backgroundColor[index],
                     strokeStyle: dataset.borderColor[index],
                     lineWidth: 1
                  }
               });
               return legend;
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Leave a comment