ng2-charts / chart.js-如何以编程方式在特定标签上设置甜甜圈/饼图颜色?

时间:2018-06-29 07:29:38

标签: angular chart.js ng2-charts

我有一个事务列表,这些事务返回status作为图表标签,而返回count作为图表数据。我的标签通常为['cancelled', 'completed', 'rejected'],但有时数据返回['cancelled', 'completed', 'error', 'pending', 'rejected]。如何为每个标签设置不同的颜色?

到目前为止,我的代码:

statusCount: StatusCount[] = [];
  loaded = false;

  // Doughnut
  public chartData = [];
  public chartLabels = [];

  public chartType = 'doughnut';

  public chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      position: 'right'
   }
  };

  private chartColors: any[] = [{ backgroundColor: ['#E91E63', '#00BFA5', '#ff1744'] }];

  constructor(
    private apiService: ApiService
  ) { 
  }

  ngOnInit() {
    this.getTransactionStatus();
  }

  getTransactionStatus() {
    this.apiService.getTransactionStatus().subscribe((res: any) => {
      this.statusCount = res;
      for (const i of this.statusCount) {
        this.chartData.push(i.count);
        this.chartLabels.push(i.status);
      }
      this.loaded = true;
    }, error => {
      console.log(error);
    });
  }

1 个答案:

答案 0 :(得分:1)

您也可以在chartColors方法中设置getTransactionStatus

它看起来像这样(假设您的statusCount对象具有color属性:

public chartColors: any[] = [{ backgroundColor: [] }];

  constructor(
    private apiService: ApiService
  ) { 
  }

  ngOnInit() {
    this.getTransactionStatus();
  }

  getTransactionStatus() {
    this.apiService.getTransactionStatus().subscribe((res: any) => {
      this.statusCount = res;
      for (const i of this.statusCount) {
        this.chartData.push(i.count);
        this.chartLabels.push(i.status);
        this.chartColors[0].backgroundColor.push(i.color);
      }
      this.loaded = true;
    }, error => {
      console.log(error);
    });
  }

请注意,您的chartColors对象应该是公共的(例如chartDatachartLabelse等),以便HTML可见(它将在开发人员模式下工作,但不会)除非是公开的,否则不要建造。

相关问题