Chartjs-Multi Level Color in Doughnut Chart in ng2-charts

0👍

Instead of defining the data as a MultiDataSet, you can define it as an array of ChartDataSets and define the colors on each dataset as follows.

doughnutChartData: ChartDataSets[] = [
    {
      label: 'Dataset A',
      data: [33, 21, 9, 9, 11, 13, 5 ],
    }, {
      label: 'Dataset B',
      data: [35, 20, 10, 10, 15, 15, 10 ],
    }, {
      label: 'Dataset C',
      data: [40, 15, 5, 15, 20, 5, 20 ],
    }    
  ];

  ngOnInit() {
    this.doughnutChartData.forEach(ds => {
      ds.backgroundColor = ['red', 'black', 'green', "purple", "yellow", "blue", "grey"];
      ds.hoverBackgroundColor = ["lightgrey", "grey", "lightgrey", "grey","lightgrey", "grey", "lightgrey"];
    });
  }

The HTML template would have to look as follows:

<canvas baseChart
  [chartType]="doughnutChartType"
  [labels]="doughnutChartLabels"    
  [datasets]="doughnutChartData"
  [options]="doughnutChartOption">
</canvas>

Please take a look at this StackBlitz and see how it works.

Leave a comment