Angular 8 & ChartJs change color in pie chart

Viewed 5013

I am trying to change the default pie chart color. but all 3 pie chart arc showing red color. Apply the first color in pieColor array to all arc. I am using chart.js 2.9.3, ng2-charts 2.3.0 & angular 8. Also, I am trying a different color format like hex code or RGB but not working.

pie-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart 
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [colors]="pieColor
    [chartType]="doughnutChartType">
  </canvas>
</div>

pie-chart.component.ts

import { Component } from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label } from 'ng2-charts';

@Component({
  selector: 'app-doughnut-chart',
  templateUrl: './doughnut-chart.component.html',
  styleUrls: ['./doughnut-chart.component.css']
})

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['BMW', 'Ford', 'Tesla'];
  doughnutChartData: MultiDataSet = [
    [55, 25, 20]
  ];
  doughnutChartType: ChartType = 'doughnut';
  public pieColor: Color[] = [
     { backgroundColor: 'red' },
     { backgroundColor: 'green' },
     { backgroundColor: 'blue' }
  ]
}

Output enter image description here

2 Answers

Your issue is the form of the colors array. Instead of defining multiple backgroundColor arrays with each having one color, you should only define one array which has multiple colors. Try below and it should work:

Template

<div class="chart-wrapper">
  <canvas baseChart [data]="doughnutChartData" [labels]="doughnutChartLabels" [colors]="colors"
    [chartType]=" doughnutChartType">
  </canvas>
</div>

Controller

export class AppComponent {
  doughnutChartLabels: Label[] = ['BMW', 'Ford', 'Tesla'];

  doughnutChartData: MultiDataSet = [
    [
      55,
      25,
      20
    ]
  ];

  doughnutChartType: ChartType = 'doughnut';

  colors: Color[] = [
    {
      backgroundColor: [
        'red',
        'green',
        'blue'
      ]
    }
  ];

}

In your typescript define which colors you want to specify for each section

public donutColors=[
    {
      backgroundColor: [
          'rgba(92, 184, 92,1)',
          'rgba(255, 195, 0, 1)',
          'rgba(217, 83, 79,1)',
          'rgba(129, 78, 40, 1)',
          'rgba(129, 199, 111, 1)'
    ]
    }
  ];

and in html add

[colors]="donutColors"
Related