ChartJS Charts.js转换负数数据

fjaof16o  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(193)

在我的长条图中,我得到一组数字做为数据。一个是收入,另一个是支出。我想将两者都显示为正数,以便于比较。问题是,我不知道在何处将支出数据转换成正数。
我已经在ngOnInit中使用Math.abs(this.barData[1])尝试过了,但是我得到了类型错误:类型为'(number)的参数|散点图数据点|BubbleDataPoint)[]'无法指派给型别' number '的参数。
有人能帮帮我吗?

barLabel = ["13.03.2022"];
barData = [[645.54], [- 114.24]];

@Input() barData!: (number | ScatterDataPoint | BubbleDataPoint)[][];
@Input() barLabel!: string[];

public barChartType: ChartType = "bar";
public barChartData: ChartConfiguration["data"];
defaultBarChartData: Partial<ChartConfiguration['data']>;

ngOnInit(): void {
  this.defaultBarChartData = {
    labels: this.barLabel,
    datasets: [
      {
        data: this.barData[0],
        label: "Income",
        backgroundColor: "#3ABD32",
      },
      {
        data: this.barData[1],
        label: "Expense",
        backgroundColor: "#E02A45",
      },
    ],
  };

  if (
    this.barData !== undefined &&
    this.barLabels !== undefined &&
    Array.isArray(this.barData) &&
    this.barData.length > 0 &&
    Array.isArray(this.barLabels) &&
    this.barLabels.length > 0 
  ) 
  {
    this.barChartData = {
      ...this.defaultBarChartData,
      ...{ labels: [" "] },
    } as ChartConfiguration['data'];
    this.barChartData.datasets[0].data = this.barData[0];
   } else {
    throw new Error('Charts must have their data and labels inputs defined.');
   }
  }

public barChartOptions: ChartConfiguration["options"] = {...}
5lwkijsr

5lwkijsr1#

根据ts声明,Math.abs需要输入一个数字。所以你需要在数组后面指定[0]来得到这个数字。然后你需要再次把它变成一个数组,因为chart.js需要一个数组。所以你的代码看起来像这样:

barLabel = ["13.03.2022"];
barData = [[645.54], [- 114.24]];

@Input() barData!: (number | ScatterDataPoint | BubbleDataPoint)[][];
@Input() barLabel!: string[];

public barChartType: ChartType = "bar";
public barChartData: ChartConfiguration["data"];
defaultBarChartData: Partial<ChartConfiguration['data']>;

ngOnInit(): void {
  this.defaultBarChartData = {
    labels: this.barLabel,
    datasets: [
      {
        data: [Math.abs(this.barData[0][0])],
        label: "Income",
        backgroundColor: "#3ABD32",
      },
      {
        data: [Math.abs(this.barData[1][0])],
        label: "Expense",
        backgroundColor: "#E02A45",
      },
    ],
  };

  if (
    this.barData !== undefined &&
    this.barLabels !== undefined &&
    Array.isArray(this.barData) &&
    this.barData.length > 0 &&
    Array.isArray(this.barLabels) &&
    this.barLabels.length > 0 
  ) 
  {
    this.barChartData = {
      ...this.defaultBarChartData,
      ...{ labels: [" "] },
    } as ChartConfiguration['data'];
    this.barChartData.datasets[0].data = this.barData[0];
   } else {
    throw new Error('Charts must have their data and labels inputs defined.');
   }
  }

public barChartOptions: ChartConfiguration["options"] = {...}

相关问题