代码之家  ›  专栏  ›  技术社区  ›  Hoàng Nguyễn

ng2 charts/chart.js-如何通过编程设置特定标签上的圆环图/饼图颜色?

  •  0
  • Hoàng Nguyễn  · 技术社区  · 6 年前

    我有一个返回的交易列表 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 回复  |  直到 6 年前
        1
  •  1
  •   William Moore    6 年前

    你可以设定 chartColors getTransactionStatus

    statusCount

    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);
        });
      }
    

    图表颜色 chartData ,请 chartLabelse