gpt4 book ai didi

javascript - 将 firebase 数据绘制到 ChartJS

转载 作者:行者123 更新时间:2023-11-29 23:05:20 25 4
gpt4 key购买 nike

我在根据 firebase 数据在 chartjs 中绘制数据时遇到问题。 ChartJS 仅显示列表中的最后一个数据。我能够获取对象数据,但 chartJS 仅在图表上绘制最后和最新数据。

链接:

firebase database node chartjs only shows the last data

function gotData(data){
//console.log(data.val());

var records = data.val();
var keys = Object.keys(records);

console.log(keys);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
var sys = records[k].systolicpressure;
var dia = records[k].diastolicpressure;
var time = records[k].time;
console.log(sys, dia, time);


var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [time],
datasets: [{
label: 'Blood Pressure Graph',
data: [sys]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
time: {
unit:'hour'
}
}]
}
}
});
}
}

最佳答案

不是在每次循环迭代时都定义对象数据:

data: {
labels: [time],
datasets: [{
label: 'Blood Pressure Graph',
data: [sys]
}]
}

尝试使用 for 循环构建数据数组,并在循环结束时创建图表:

function gotData(data){
//console.log(data.val());

var records = data.val();
var keys = Object.keys(records);
var chartData = [];
console.log(keys);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
var sys = records[k].systolicpressure;
var dia = records[k].diastolicpressure;
var time = records[k].time;
chartData.push(sys);
console.log(sys, dia, time);
}

var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [time],
datasets: [{
label: 'Blood Pressure Graph',
data: chartData
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes: [{
time: {
unit:'hour'
}
}]
}
}
});
}

希望我没有把括号弄乱 :) 让我知道它是如何工作的。

关于javascript - 将 firebase 数据绘制到 ChartJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54866991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com