33

I want to set dynamically a color for each part of Pie Chart. Since the chart is dynamically created from database I want for each part that is added to the chart(from database) a different color.

I was trying to do this:

$(document).ready(function() {
$.ajax({
url: "http://localhost/chartjs/projects_chart.php",
method: "GET",
success: function(data) {
    console.log(data);
    var ict_unit = [];
    var efficiency = [];
    var dynamicColors = function() {
        var r = Math.floor(Math.random() * 255);
        var g = Math.floor(Math.random() * 255);
        var b = Math.floor(Math.random() * 255);
        return "rgb(" + r + "," + g + "," + b + ")";
    };

    for (var i in data) {
        ict_unit.push("ICT Unit " + data[i].ict_unit);
        efficiency.push(data[i].efficiency);
         var coloR=dynamicColors();
    }
    var chartData = {

        labels: ict_unit,
        datasets: [{
            label: 'Efficiency ',
            //strokeColor:backGround,

            backgroundColor: [coloR],

            borderColor: 'rgba(200, 200, 200, 0.75)',
            //hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
            hoverBorderColor: 'rgba(200, 200, 200, 1)',
            data: efficiency
        }]
    };

    var ctx = $("#my-canvas");
    var barGraph = new Chart(ctx, {
        type: 'pie',
        data: chartData
    })
},
error: function(data) {

    console.log(data);
   },
  });
 });

But I only get one color for the first part of the pie chart.

Could you help me?

ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110
Nda.S
  • 419
  • 1
  • 6
  • 12

3 Answers3

71

You should create a separate array for colors ( just like the ict_unit and efficiency ), instead of assigning a random color value each time to the coloR variable.

Here is the revised version of your code :

$(document).ready(function() {
   $.ajax({
      url: "https://jsonblob.com/api/jsonBlob/a7176bce-84e0-11e7-8b99-016f34757045",
      method: "GET",
      success: function(data) {
         console.log(data);
         var ict_unit = [];
         var efficiency = [];
         var coloR = [];

         var dynamicColors = function() {
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            return "rgb(" + r + "," + g + "," + b + ")";
         };

         for (var i in data) {
            ict_unit.push("ICT Unit " + data[i].ict_unit);
            efficiency.push(data[i].efficiency);
            coloR.push(dynamicColors());
         }
         var chartData = {

            labels: ict_unit,
            datasets: [{
               label: 'Efficiency ',
               //strokeColor:backGround,

               backgroundColor: coloR,

               borderColor: 'rgba(200, 200, 200, 0.75)',
               //hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
               hoverBorderColor: 'rgba(200, 200, 200, 1)',
               data: efficiency
            }]
         };

         var ctx = $("#my-canvas");
         var barGraph = new Chart(ctx, {
            type: 'pie',
            data: chartData
         })
      },
      error: function(data) {

         console.log(data);
      },
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="my-canvas"></canvas>
ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110
  • I know it is old, but it would be better if you choose de colors in a deterministic case, saving you from the odd case where you get a repeated color and allowing you to choose a range matching your palette. – juanlugm Jun 21 '18 at 21:14
  • 2
    I did it by passing two parameters to your function, i and data.length. You can pick the color by changing the offset. [https://jsfiddle.net/742zut83/934/ ] – juanlugm Jun 21 '18 at 21:39
  • instead of dynamic color i want highest marks should be display in red color please any one suggest me – siddalingappa M May 01 '19 at 11:04
  • In @juanlugm code I had to use `Math.round` for the `r, g, b` values. :) – bhathiya-perera Mar 21 '21 at 10:48
3

An example snippet for rgb color picker between 235 and 52

const randomNum = () => Math.floor(Math.random() * (235 - 52 + 1) + 52);

const randomRGB = () => `rgb(${randomNum()}, ${randomNum()}, ${randomNum()})`;

console.log(randomRGB());

Resource:

serdarsen
  • 193
  • 2
  • 8
0

Another consideration can be have a Set and avoid color repetition, like this:

let data = []; // Some data
let data_labels = []; // Some data labels
let randomBackgroundColor = [];
let usedColors = new Set();

let dynamicColors = function() {
    let r = Math.floor(Math.random() * 255);
    let g = Math.floor(Math.random() * 255);
    let b = Math.floor(Math.random() * 255);
    let color = "rgb(" + r + "," + g + "," + b + ")";

    if (!usedColors.has(color)) {
        usedColors.add(color);
        return color;
    } else {
        return dynamicColors();
    }
};

for (let i in data) {
    randomBackgroundColor.push(dynamicColors());
}

let pie_config = {
    type: 'pie',
    data: {
        datasets: [{
            data: data,
            backgroundColor: randomBackgroundColor,
            label: 'Label'
        }],
        labels: data_labels
    },
    options: {
        responsive: true
    }
};
renelhs
  • 57
  • 4