如何使用Chart.js和ng2-charts构建一些图表,使用每月的一组revenus和预算作为数据源?

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

我想使用Chart.js和ng2-charts构建一些图表。我有一系列数据(一周)。我想知道如何根据每个日期构建一系列revenu值和预算值。这些值将显示在图表的Y轴上,X轴包含标签([01,02,03,04,05,...,31]),它们是月份日期:

week = [
         {
            date = "2019-03-01",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-02",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-03",
            revenu = 1000,
            budget = 800
         },
         {
            date = "2019-03-04",
            revenu = 1000,
            budget = 800
         },
         ...
       ];
       

public monthChartLabels= [01, 02, 03, 04, 05, ..., 31];
public monthChartData = [
  {
    data: [ ? ] // Array of revenu-values according to each date
  },
  {
    data: [ ? ] // Array of budget-values according to each date
  }  
];
 
<canvas
        baseChart
        [chartType]=" 'line' "
        [datasets]="monthChartData"
        [labels]="monthChartLabels"
        [options]="monthLabels"
        [legend]="true"
        (chartHover)="onChartHover($event)">
</canvas>
arrays typescript chart.js ng2-charts
1个回答
0
投票

Shalom Eli,你应该将map原始数据加到图表的data数组中:week.map(e => e.revenu)用于revenu数据集,week.map(e => e.budges)用于budget数据集。

更新

根据您的评论,您希望将week数组转换为按每个记录的月份日期键入的地图:

week.reduce((acc,v)=> ({
  ...acc,
  [new Date(v.date).getDate()]: v
}), {})

然后使用您的labels数组从此映射中获取每个值:

revenuData = labels.map(r => this.weekMap[+r] && this.weekMap[+r].revenu);
budgetData = labels.map(r => this.weekMap[+r] && this.weekMap[+r].budget);

看到这个更新的stackblitz:https://stackblitz.com/edit/ng2-charts-line-template-3dfmxn

enter image description here

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