我想使用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>
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