Angular 8和ChartJs更改饼图中的颜色

问题描述 投票:1回答:1

我正在尝试更改默认的饼图颜色。但所有3个饼形图的弧线均显示红色。将pieColor数组中的第一种颜色应用于所有圆弧。我正在使用chart.js 2.9.3,ng2-charts 2.3.0和angular8。此外,我正在尝试使用其他颜色格式,例如十六进制代码或RGB,但无法正常工作。

pie-chart.component.html

<div class="chart-wrapper">
    <canvas baseChart 
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [colors]="pieColor
    [chartType]="doughnutChartType">
  </canvas>
</div>

pie-chart.component.ts

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

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

export class DoughnutChartComponent {

  doughnutChartLabels: Label[] = ['BMW', 'Ford', 'Tesla'];
  doughnutChartData: MultiDataSet = [
    [55, 25, 20]
  ];
  doughnutChartType: ChartType = 'doughnut';
  public pieColor: Color[] = [
     { backgroundColor: 'red' },
     { backgroundColor: 'green' },
     { backgroundColor: 'blue' }
  ]
}

输出enter image description here

angular chart.js ng2-charts
1个回答
0
投票

您的问题是颜色数组的形式。而不是定义多个backgroundColor数组,每个数组只有一种颜色,您应该只定义一个具有多种颜色的数组。请尝试以下操作,它应该可以工作:

模板

<div class="chart-wrapper">
  <canvas baseChart [data]="doughnutChartData" [labels]="doughnutChartLabels" [colors]="colors"
    [chartType]=" doughnutChartType">
  </canvas>
</div>

Controller

export class AppComponent {
  doughnutChartLabels: Label[] = ['BMW', 'Ford', 'Tesla'];

  doughnutChartData: MultiDataSet = [
    [
      55,
      25,
      20
    ]
  ];

  doughnutChartType: ChartType = 'doughnut';

  colors: Color[] = [
    {
      backgroundColor: [
        'red',
        'green',
        'blue'
      ]
    }
  ];

}
© www.soinside.com 2019 - 2024. All rights reserved.