I'm having a problem with plotting data to ChartJS from Firestore data. For some reason it only shows a single value on the bottom of the graph and random number on y-axis instead of date. I hope someone can help me. My firestore: firestore My chart: chart
Here's what I have so far.
db.collection('Items').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
var item= doc.data();
var price= item.price;
var date = item.date;
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [date],
datasets: [{
label: 'Items',
data: [price],
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
// Container for pan options
pan: {
// Boolean to enable panning
enabled: true,
// Panning directions.
mode: 'x',
speed: 1
},
// Container for zoom options
zoom: {
// enable zooming
enabled: true,
// Zooming directions.
mode: 'x',
}
}
});
})
})
For each doc
in the snapshot
you are doing var myChart = new Chart()
, creating a new chart each time .
You should build your data
and labels
arrays in the forEach
and then ( outside the forEach
) create a new chart and pass it the arrays.
Something like the following (not tested):
var labelsArray = [];
var dataArray = [];
db.collection('Items').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
var item = doc.data();
var price = item.price;
dataArray.push(price);
var date = item.date;
labelsArray.push(date);
});
});
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labelsArray,
datasets: [{
label: 'Items',
data: dataArray ,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
// Container for pan options
pan: {
// Boolean to enable panning
enabled: true,
// Panning directions.
mode: 'x',
speed: 1
},
// Container for zoom options
zoom: {
// enable zooming
enabled: true,
// Zooming directions.
mode: 'x',
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.