var voltagedata1 = [];
batterybank1.forEach(function(element){
var voltage = {x: element.timestamp, y:element.voltage};
voltagedata1.push(voltage);
})
data: voltagedata1
例如,此代码有效:
data: [
{x: '2019-08-12 09:40:15', y:4}, {x: '2019-08-13 09:40:15', y:5}, {x: '2019-08-14 09:40:15', y:6},
],
然后尝试如下遍历数组:
batterybank1.forEach(function(element){
console.log(element)
"{x:\'element.timestamp', y:element.voltage},"
})
console.log(element)提供正确的输出,但是图表未更新...在控制台上,我没有警告/错误-只是图形没有输出。
以下内容也不起作用,仅输出console.log,但不更新图形。
batterybank1.forEach(function(element){
console.log(element)
"{x:\'2019-08-12 09:40:15', 1},"
})
答案 0 :(得分:1)
the documentation中对此进行了解释,您可以一次将点添加到图表中,如下所示:
batterybank1.forEach(function(element){
chart.data.datasets[0].data.push(element);
})
这是假设element
与data
中的点具有相同的格式。
此后,您需要调用chart.update();
以显示新数据。
下面是一个有效的示例:
let data = [{t: '2019-08-12 09:40:15', y:4}, {t: '2019-08-13 09:40:15', y:5}, {t: '2019-08-14 09:40:15', y:6}, {t: '2019-08-15 09:40:15', y:7}];
var chart = new Chart(document.getElementById('cht'), { type:'bar', data:
{
datasets:[{
label: 'CHRT - Chart.js Corporation',
backgroundColor: '#ff0000',
borderColor: '#ff0000',
type: 'bar',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2,
data: data}]
}, options:{
scales: {
xAxes: [
{
type: 'time',
distribution: 'series',
ticks:
{
source: 'data',
autoSkip: true
}
}]
}
} });
document.getElementById('addPoints').addEventListener('click', function() {
let extra = [{t: '2019-08-16 09:40:15', y:4}, {t: '2019-08-17 09:40:15', y:5}, {t: '2019-08-18 09:40:15', y:6}, {t: '2019-08-19 09:40:15', y:7}];
extra.forEach(p =>
{
chart.data.datasets[0].data.push(p);
});
chart.update();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
<button id="addPoints">Add Points</button>
<canvas id="cht" class="chartjs" width="770" height="385" style="display: block; width: 770px; height: 385px;">