1👍
✅
Instead of defining the object data on every loop iteration:
data: {
labels: [time],
datasets: [{
label: 'Blood Pressure Graph',
data: [sys]
}]
}
Try to build an array of data using the for loop, and at the end of the loop create your chart:
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'
}
}]
}
}
});
}
Hope I didn’t get the parentheses all messed up 🙂 Let me know how this works.
0👍
I was able to solve this problem by placing an array variable outside the loop and pushing the data inside it and placing the array variable inside the chartJS data.
var form = document.getElementById('uidgetforchart');
var uid = form.elements.uidgetthis.value;
var ctx = document.getElementById("myChart");
console.log(uid);
var hourOfDay;
hourOfDay = getjustHoursOfDay();
function newDate() {
return moment().add(days, 'd');
}
var ref = database.ref('Blood Pressure Posts/Registered User/'+uid);
ref.on('value', gotData, errData);
function gotData(data){
//console.log(data.val());
var records = data.val();
var keys = Object.keys(records);
var systolicdata = [];
var systolictime = [];
console.log(keys);
for (var i = 0; i < keys.length; i++){
var k = keys[i];
console.log(k);
var sys = records[k].systolicpressure;
console.log(sys);
var dia = records[k].diastolicpressure;
var time = records[k].time;
var chartDataSys = [];
var chartDataSysTime = [];
chartDataSys.push(sys);
systolicdata.push(sys);
systolictime.push(time);
chartDataSysTime.push(time);
//chartDataTime.push(time);
// console.log(chartDataSys, chartDataSysTime);
// var datachart = {
// labels: 'Blood Pressure Chart',
// borderColor:'red',
// data: [
// {
// label: "My First dataset",
// data: [1, 3, 4, 2, 1, 4, 2],
// }
// ]
// };
}
console.log(systolicdata);
var myChart = new Chart(ctx, {
type: 'line',
data:
{
labels: systolictime,
datasets: [{
label: "My First dataset",
data: systolicdata,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}],
xAxes:[{
type: 'time',
time: {
format: "HH:mm",
unit: 'hour',
unitStepSize: 1,
displayFormats: {
'minute': 'HH:mm',
'hour': 'HH:mm',
min: '00:00',
max: '23:59'
},
}}]
}
}
});
}
function errData(data){
console.log("Error");
console.log(err);
}
function getjustHoursOfDay() {
var hours=[];
for (var i = 0; i < 23; i++) {
var _time;
if (i<10) {
_time="0"+i+":00";
}else {
_time=i+":00";
}
hours.push(_time);
}
var lastOfDay="23:59";
hours.push(lastOfDay);
return hours;
}
Source:stackexchange.com