Chartjs-Legend color not working with randomly generated background colors in chartjs pie chart

0👍

Send array (["red", "blue","orange"] as value for backgroundColor.

Simple forEach example:

var colors = [];
labels.forEach((element) => {
  var hex_color = getRandomColorHex();
  colors.push(hex_color);
})
console.log(colors) /* ["#5076FA", "#2832C4", "#36DEA3", "#7A940B", "#FD8E0D", "#6214DF", "#9CF566", "#71459C", "#98F6B5", "#B111A4", "#AAB800", "#D8DA57", "#836BD9"] */

And use this array as a value for backgroundColor:

backgroundColor: colors,

Working example:

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

var labels =  ["Mar-2019","Apr-2019","May-2019","Jun-2019","Jul-2019","Aug-2019","Sep-2019","Oct-2019","Nov-2019","Dec-2019","Jan-2020","Feb-2020","Mar-2020"];
var dataSet = {"ADVERTS_PUBLISHED":["0","0","1","0","4","0","2","0","1","0","1","1","1"],"ADVERT_ACTIONS":["5","1","2","1","2","0","1","0","1","2","1","0","0"],"VIEWS":["34","1","4","3","5",0,"1",0,"2","5","6",0,0],"CLICKS":["13","0","3","3","3",0,"1",0,"2","4","6",0,0],"SUBMITTED":["3",0,"2","2","2",0,"1",0,"7","3","2",0,0],"PENDING":["0",0,"2","0","0",0,"0","2","0","1","0",0,0],"FILTERED":["3",0,"1","2","2",0,"1","0","7","3","0",0,0],"SHORTLISTED":["0",0,"0","2","0",0,"0","5","0","0","0",0,0],"REGRETTED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"INTERVIEWED":["0",0,"0","2","0",0,"0","1","0","0","0",0,0],"OFFERED":["1",0,"0","0","1",0,"11","0","0","0","0",0,0],"OFFERED_AND_DECLINED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"REGRETTED_AND_COMM":["0",0,"0","0","0",0,"0","1","0","0","2",0,0],"ACTUAL_HIRED":["0",0,"0","0","0",0,"0","0","0","1","0",0,0]};

var colors = [];
labels.forEach((element) => {
  var hex_color = getRandomColorHex();
  console.log("hello" + hex_color);
  colors.push(hex_color);
})


var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: labels,
    datasets: [{
      label: 'Adverts Published',
      data: dataSet.ADVERTS_PUBLISHED,
      backgroundColor: colors,
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    //  onClick: graphClickEvent,
    hover: {
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});


function getRandomColorHex() {
  var hex = "0123456789ABCDEF",
      color = "#";
  for (var i = 1; i <= 6; i++) {
    color += hex[Math.floor(Math.random() * 16)];
  }
  return color;
} 
div{
  border: 1px solid red;
}
<div id="">
   <canvas class="chart__graph" id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Leave a comment