如何为chart.js饼图数据集分配不同的背景颜色?

时间:2019-08-03 19:11:50

标签: chart.js

我能够在下面创建一个chart.js饼图:

this.httpClient.get(this.url).subscribe((res: Stock[]) => {
      res.forEach(holding => {
        this.company.push(holding.company);
        this.price.push(holding.price);
      });
      this.chart = new Chart('canvas', {
        type: 'pie',
        data: {
          labels: this.company,
          datasets: [
            {
              data: this.price,
              borderColor: '#3cba9f',
              backgroundColor: 'rgba(35, 206, 107, 0.5)',
              fill: false
            } 
          ]
        },
        options: {
          legend: {
            display: true
          }     
        }
      });
    });

此刻,饼图的每个部分都具有与我上面指定的相同的backgroundColor

我的问题是我希望馅饼的每个部分都具有不同的背景色。有人可以告诉我如何使用上述代码进行此更改吗?

1 个答案:

答案 0 :(得分:1)

您可以将字符串(颜色)数组传递给backgroundColor

backgroundColor: ['red', 'green', 'blue']

示例:

new Chart(document.getElementById("chart"), {
  type: "pie",
  data: {
    datasets: [{
      data: [1, 2, 3],
      backgroundColor: ['red', 'green', 'blue']
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>