出于可视化的目的,我试图将数据添加到图表,同时每500毫秒同时从图表中删除第一个数据点。
当我自己执行.addData()
或removeData()
时,它都起作用,但是当我尝试将它们组合成一个函数同时运行时,它们都不起作用。
是否可以创建此函数以同时添加和删除数据,或者至少在添加新的最后一个数据点后不久删除第一个数据点?
以下是数据和设置:
var ctx = document.getElementById('myChart').getContext('2d');
ctx.height = 220;
var data = {
"labels": [
"0",
"1",
"2",
"3",
"4"
],
"datasets": [
{
"label": "2014",
"backgroundColor": "#0055FA",
"fill": true,
"data": [
"50",
"40",
"55",
"35",
"45",
"50",
"15",
"100"
],
"borderColor": "transparent",
"borderWidth": "0",
"pointBackgroundColor":"#ffffff"
}
]
};
var options = {
"title": {
"display": false,
"text": "Ad Revenue Comparison 2014-2015",
"position": "bottom",
"fullWidth": true,
"fontColor": "#aa7942",
"fontSize": 16
},
"legend": {
"display": false,
"fullWidth": true,
"position": "top"
},
"scales": {
"yAxes": [
{
"ticks": {
"beginAtZero": true,
"display": true
},
"gridLines": {
"display": false
},
"scaleLabel": {
"display": false,
"labelString": "USD in Millions"
},
"display": false
}
],
"xAxes": {
"0": {
"ticks": {
"display": false
},
"display": false,
"gridLines": {
"display": false
},
"scaleLabel": {
"display": false
}
}
}
},
"tooltips": {
"enabled": false
},
"elements": {
"arc": {
"backgroundColor": "#009BD0"
},
"line": {
"backgroundColor": "#009BD0",
"fill": true,
"borderColor": "#e2fdff"
},
"point": {
"radius": 3,
"pointStyle": "circle",
"backgroundColor": "#ffffff"
}
}
};
以下是功能:
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
setInterval(function(){
addData(myChart,"4",Math.floor(Math.random() * 60));
removeData(myChart);
}, 500);
//setInterval(function(){ removeData(myChart); }, 500);
</script>