2

I have a pie chart like this:

this.canvas = document.getElementById('chart');
    this.ctx = this.canvas.getContext('2d');
    const myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
        labels: names,
        datasets: [{
          label: '# of dogs',
          data: data,
          backgroundColor: color???,
          borderWidth: 1
        }]
      },
      options: {
        responsive: false,
        display: true
      }
    });

data is not a fixed data. It is an array and can contain different data. How can I make that each piece of the pie chart has a different color?

Thanks!

RAL
  • 297
  • 2
  • 4
  • 8
  • You can try this https://stackoverflow.com/questions/24896562/changing-color-of-specific-chartjs-point/24928967#24928967 . I am not used this, but I searched on baidu.com – Fupeng Wang Aug 30 '18 at 14:11

2 Answers2

5

this is my suggestion : Step 1

colors=[];

Step 2

for(let i=0;i<this.data.length;i++){
      this.colors.push('#'+Math.floor(Math.random()*16777215).toString(16));
}

Stap 3

data: data,
backgroundColor: this.colors
.....
SAAD BELEFQIH
  • 352
  • 3
  • 8
3

Generate a random color

 function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }

this.canvas = document.getElementById('chart');
    this.ctx = this.canvas.getContext('2d');
    const myChart = new Chart(this.ctx, {
      type: 'pie',
      data: {
        labels: names,
        datasets: [{
          label: '# of dogs',
          data: data,
          backgroundColor: getRandomColor(),
          borderWidth: 1
        }]
      },
      options: {
        responsive: false,
        display: true
      }
    });
Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79