Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js ng2-charts colors in pie chart not showing

I am using ng-2 charts and while I can display the pie chart correctly, I am not able to change the colors of the different pie slices.

It seems like there is a bug where all the slices of the pie get the first color declared in the object (in this case red).

My component.ts looks like :

public pieChartColors:Array<any> = [
  {
    backgroundColor: 'red',
    borderColor: 'rgba(135,206,250,1)',
  },
  {
    backgroundColor: 'yellow',
    borderColor: 'rgba(106,90,205,1)',
  },
  {
    backgroundColor: 'rgba(148,159,177,0.2)',
    borderColor: 'rgba(148,159,177,1)',

  }
];

// Pie
public pieChartLabels:string[] = ['First Set', 'Sales', 'Mail'];
public pieChartData:number[] = [300, 500, 100];
public pieChartType:string = 'pie';

My view:

<canvas
  [chartType]="pieChartType"
  [colors]="pieChartColors"
  [data]="pieChartData"
  [labels]="pieChartLabels"
  baseChart
></canvas>
like image 827
greatTeacherOnizuka Avatar asked Jun 20 '17 13:06

greatTeacherOnizuka


2 Answers

Try something like the following ...

public pieChartColors: Array < any > = [{
   backgroundColor: ['red', 'yellow', 'rgba(148,159,177,0.2)'],
   borderColor: ['rgba(135,206,250,1)', 'rgba(106,90,205,1)', 'rgba(148,159,177,1)']
}];
...

not a 'ng2-charts' pro, but afaik this should work.

like image 176
ɢʀᴜɴᴛ Avatar answered Sep 19 '22 08:09

ɢʀᴜɴᴛ


Solved this problem by adding *ngIf="pieChartLabels && pieChartData" condition in the HTML template:

<div class="card">
    <div class="card-header">
        Pie Chart
    </div>
    <div class="card-body">
        <div class="chart-wrapper" *ngIf="pieChartLabels && pieChartData">
            <canvas baseChart class="chart"
                [data]="pieChartData"
                [labels]="pieChartLabels"
                [chartType]="pieChartType"
                (chartHover)="chartHovered($event)"
                (chartClick)="chartClicked($event)">
            </canvas>
        </div>
    </div>
</div>
like image 31
Salahudin Malik Avatar answered Sep 19 '22 08:09

Salahudin Malik