ng2-图中的甜甜圈图中的多级颜色

时间:2020-09-14 14:14:37

标签: angular typescript chart.js ng2-charts

我开始使用Chart.js中的ng2-ChartsAngular。现在我正在做甜甜圈图,想要做一个多级图表,但是不能更改每个级别的颜色。我选择的颜色仅在第一个级别上,而不在其他级别上。

这是我的 doughnut-chart.component.ts

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

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

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['SPD', 'CDU', 'Grüne', "Linke", "FDP", "AFD", "Andere"];
  doughnutChartData: MultiDataSet = [
    [33, 21, 9, 9, 11, 13, 5 ],
    [35, 20, 10, 10, 15, 15, 10 ],
    [40, 15, 5, 15, 20, 5, 20 ]
  ];

  public doughnutChartColors: Color[] = [
    {
      backgroundColor:
      [
      'red',
      'black',
      'green',
      "purple",
      "yellow",
      "blue",
      "grey"
      ],
      hoverBackgroundColor:
      [
      "lightgrey",
      "grey",
      "lightgrey",
      "grey",
      "lightgrey",
      "grey",
      "lightgrey",
      ],
    }
  ];

  doughnutChartType: ChartType = 'doughnut';

  doughnutChartOption: ChartOptions = {}
    
}

有人知道该怎么办吗?我在互联网上没有找到有关此主题的任何信息。

1 个答案:

答案 0 :(得分:0)

您可以将数据定义为MultiDataSet的数组,然后将每个ChartDataSets的颜色定义如下,而不是将数据定义为dataset

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"];
    });
  }

HTML模板必须如下所示:

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

请查看此StackBlitz并查看其工作原理。