我正在尝试使用Rickshaw创建一个漂亮的占位符图表,显示随机数据的实时更新,如下所示:
var series = [[], []];
var random = new Rickshaw.Fixtures.RandomData(150);
for(var i = 0; i < 80; i++) {
random.addData(series);
}
var throughput = new Rickshaw.Graph( {
element: document.querySelector("#throughput_chart"),
width: "300",
height: "200",
renderer: "line",
series: [{
color: "gold",
data: series[0]
}]
});
var alerts = new Rickshaw.Graph( {
element: document.querySelector("#alerts_chart"),
width: "300",
height: "200",
renderer: "line",
series: [{
color: "red",
data: series[1]
}]
});
throughput.render();
alerts.render();
setInterval(function() {
random.addData(series);
throughput.update();
alerts.update();
/* XXX: This causes the data to stop drawing properly
series.forEach(function(s) {
s.shift();
});
*/
}, 1000);
这是有效的,除了注释掉的部分。实际上,它不断添加数据,这意味着图形变得越来越拥挤。我希望每次添加新项目时都能删除第一个项目,以便使图表保持相同数量的数据点,但是当我快速放入该代码时会导致图形不能显示任何数据,即使console.log
显示数组仍然充满数据。
我如何才能完成这项工作,以便我一次只显示固定数量的数据点?
答案 0 :(得分:11)
在人力车(http://code.shutterstock.com/rickshaw/examples/fixed.html)的文档示例的引导下,我已经把你所需要的东西拼凑起来了:
var tv = 50;
var throughput = new Rickshaw.Graph({
element: document.querySelector("#throughput_chart"),
width: "300",
height: "200",
renderer: "line",
series: new Rickshaw.Series.FixedDuration([{
name: 'one', color: 'gold'
}], undefined, {
timeInterval: tv,
maxDataPoints: 100,
timeBase: new Date().getTime() / 1000
})
});
var alerts = new Rickshaw.Graph({
element: document.querySelector("#alerts_chart"),
width: "300",
height: "200",
renderer: "line",
series: new Rickshaw.Series.FixedDuration([{
name: 'one', color: 'red'
}], undefined, {
timeInterval: tv,
maxDataPoints: 100,
timeBase: new Date().getTime() / 1000
})
});
for(var i = 0; i < 100; i++){
addRandomData(throughput);
addRandomData(alerts);
}
throughput.render();
alerts.render();
setInterval(function () {
addRandomData(throughput);
addRandomData(alerts);
throughput.render();
alerts.render();
}, tv);
function addRandomData(chart) {
var data = {
one: Math.floor(Math.random() * 40) + 120
};
chart.series.addData(data);
}
答案 1 :(得分:2)
据我所知,FixedDuration类不能与RandomData一起使用。我所做的是删除系列数组中的第一个数据点,以便图形不会变得拥挤,并且当添加更多数据时它会向左流动:
setInterval( function() {
random.addData(seriesData);
for (i=0; i < seriesData.length; i++){
var series0 = seriesData[i][seriesData[i].length-1];
seriesData[i].shift();
seriesData[i].push(series0);
}
graph.update();
}, 3000 );
我不完全确定为什么需要将最后添加的数据点重新添加到数组的末尾(series[x].push(seriesX)
),但它不起作用。它没有加倍最后一个数据点的效果,只添加了一个。希望这对你有用!