user9847788
user9847788

Reputation: 2435

How to assign different background colors to chart.js pie chart data set?

I am able to create a chart.js pie chart below:

this.httpClient.get(this.url).subscribe((res: Stock[]) => {
      res.forEach(holding => {
        this.company.push(holding.company);
        this.price.push(holding.price);
      });
      this.chart = new Chart('canvas', {
        type: 'pie',
        data: {
          labels: this.company,
          datasets: [
            {
              data: this.price,
              borderColor: '#3cba9f',
              backgroundColor: 'rgba(35, 206, 107, 0.5)',
              fill: false
            } 
          ]
        },
        options: {
          legend: {
            display: true
          }     
        }
      });
    });

At the moment, each segment of the pie chart has the same backgroundColor, as I have assigned it above.

My issue is that I want each segment of the pie to have a different background color. Can someone please tell me how I can make this change with the above code?

Upvotes: 0

Views: 995

Answers (1)

timclutton
timclutton

Reputation: 13004

You can pass an array of strings (colours) to backgroundColor:

backgroundColor: ['red', 'green', 'blue']

Example:

new Chart(document.getElementById("chart"), {
  type: "pie",
  data: {
    datasets: [{
      data: [1, 2, 3],
      backgroundColor: ['red', 'green', 'blue']
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>

Upvotes: 2

Related Questions