【问题标题】:Multi Level Color in Doughnut Chart in ng2-chartsng2-charts中环形图中的多级颜色
【发布时间】:2020-09-15 12:15:15
【问题描述】:

我开始使用Angular 中的Chart.jsng2-Charts。现在我在做甜甜圈图,想做一个多级图表,但不能改变每个级别的颜色。我选择的颜色只在第一级,其他都没有。

这是我的 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 = {}
    
}

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

【问题讨论】:

    标签: angular typescript chart.js ng2-charts


    【解决方案1】:

    除了将数据定义为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,看看它是如何工作的。

    【讨论】:

    • 谢谢你帮了我很多我不知道我可以在饼图/甜甜圈图中使用图表数据集
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2021-04-25
    • 2020-12-10
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多