我开始使用Angular
中的Chart.js
和ng2-Charts
。现在我在做圆环图,想做一个多级图,但不能改变每个级别的颜色。我选择的颜色只在第一个层次上,而不是在其他层次上。
这是我的甜甜圈图。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 = {}
}
有人知道该怎么办吗?我在网上找不到关于这个话题的任何信息。
您可以将数据定义为ChartDataSets
的数组,而不是将数据定义成MultiDataSet
,并按如下方式定义每个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并了解其工作原理。