ChartJS 为数组中的每个对象指定随机颜色

djp7away  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(180)

我正在用chartjs设置一个图表。图表按预期工作,但现在的问题是,要么所有的图表都会得到相同的颜色,要么每次我向图表中添加一家新公司时,所有的图表都会更改为不同的随机颜色。
现在我的代码是这样的:

allInterventionStats = new Map<number, InterventionData[]>();

async onCompanyChange(companies: Company[]) {

    for (const company of companies) {
      if (!this.companyDataCache.get(company.Id)) {
        const interventionStats = await this.adminToolsService.getInterventionUsefulnessData(company.Id).toPromise();
        this.allInterventionStats.set(company.Id, interventionStats);
        this.selectedCompanies.push(company);
      }
    }

    this.selectedCompanies = companies;

    const randomColor = () => Math.floor(Math.random() * 255);
    const colorToUse = `rgb(${randomColor()}, ${randomColor()}, ${randomColor()})`;

    for (const [companyId, interventionStats] of this.allInterventionStats) {

      const filteredData: InterventionData[] = interventionStats.filter(x => this.selectedToggleValue === '2' ? x.IsBody : !x.IsBody);

      const dataForGraph = this.calculationMonths.map(month => filteredData.find(x => month.isSame(x.Period)) || null);

      if (!dataForGraph) continue;

      const company = companies.find(x => +companyId === x.Id);
      if (!company) {
        continue;
      }

      const datasets: ChartDataset[] = [
        {
          data: dataForGraph.map(x => x !== null ? x.AverageConversationEval : null),
          fill: false,
          borderColor: colorToUse,
          backgroundColor: colorToUse,
          label: company.Name,
          cubicInterpolationMode: 'monotone',
          spanGaps: true,
          segment: {
            borderDash: (ctx) => {
              return ctx.p0.skip || ctx.p1.skip ? [this.dashLength, this.dashSpace] : undefined;
            },
          }
        },
      ];
      this.companyDataCache.set(+companyId, datasets);
    }
    this.setupChart();
  }
 setupChart() {

    if (!this.selectedCompanies.length) {
      const companyItem = this.companies.find(item => item.Id === -1);
      this.selectedCompanies = [companyItem];
    }

    const datasets: ChartDataset[] = flatten(
      this.selectedCompanies.map(dropdownItem => this.companyDataCache.get(dropdownItem.Id) || []));

    const lowerBound = 1;
    const upperBound = 5;

    const chartData: ChartData = {
      labels: this.createChartLabels(),
      datasets
    };

    this.legend = datasets
      .filter((dataset, index) => datasets
        .findIndex(x => x.label === dataset.label && x.backgroundColor === dataset.backgroundColor) === index)
      .map(dataset => ({
        text: dataset.label,
        fillStyle: dataset.backgroundColor as string,
        strokeStyle: dataset.borderColor as string
      }));
n3schb8v

n3schb8v1#

为了修复代码,我添加了一个if条件来检查该高速缓存中是否已经有该公司,这防止了它每次都分配新的颜色,因为它正确地检查了它是否已经存在。

allInterventionStats = new Map<number, InterventionData[]>();

async onCompanyChange(companies: Company[]) {

if(this.companyDataCache.has(companyId)continue;

相关问题