我开始使用Chart.js
中的ng2-Charts
和Angular
。现在我正在做甜甜圈图,想要做一个多级图表,但是不能更改每个级别的颜色。我选择的颜色仅在第一个级别上,而不在其他级别上。
这是我的 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 = {}
}
有人知道该怎么办吗?我在互联网上没有找到有关此主题的任何信息。
答案 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并查看其工作原理。