问题
I am plotting a real time graph with flot graphs.
$(function () {
var data = [];
var dataset;
var totalPoints = 100;
var updateInterval = 1000;
var now = new Date().getTime();
function GetData() {
if (data.length > totalPoints) {
data.shift();
}
var y = Math.random() * 100;
var temp = [now += updateInterval, y];
data.push(temp);
}
var options = {
series: {
lines: {
show: true,
lineWidth: 1.2,
fill: true
}
},
xaxis: {
mode: "time",
tickSize: [2, "second"],
tickFormatter: function (v, axis) {
var date = new Date(v);
if (date.getSeconds() % 20 == 0) {
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return hours + ":" + minutes + ":" + seconds;
} else {
return "";
}
},
axisLabel: "Time",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10
},
yaxis: {
min: 0,
max: 100,
tickSize: 5,
tickFormatter: function (v, axis) {
if (v % 10 == 0) {
return v + "%";
} else {
return "";
}
},
axisLabel: "CPU loading",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 6
},
legend: {
labelBoxBorderColor: "#fff"
},
grid: {
backgroundColor: "#000000",
tickColor: "#008040"
}
};
$(document).ready(function () {
GetData();
dataset = [{
label: "CPU",
data: data,
color: "#00FF00"
}];
$.plot($("#placeholder"), dataset, options);
function update() {
GetData();
$.plot($("#placeholder"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
});
I update the graph every interval. The issue is graph always starts plotting from left. I want the graph to start plotting from right and keep moving toward left as it gets updated every interval.
I tried passing data as [null, null]
but it throws exception on console.
Any better ideas here?
Fiddle
回答1:
Your time value in the call is too high (1000000 ms = 1000 seconds = ~17 minutes):
setTimeout(update, 1000000);
Also if you wish to start with a full width chart (so that the data will come in from the right), add this after your initial variable declarations to fill the chart with empty points before the measuring starts:
for (var i = 0; i < totalPoints; i++) {
data.push([now - (totalPoints - i) * updateInterval, null]);
}
Also we save the start time and only draw labels for times after the start time where we have data:
tickFormatter: function (v, axis) {
var date = new Date(v);
if (date.getTime() < startDate) {
return "";
} else ...
See this updated fiddle which includes all changes.
来源:https://stackoverflow.com/questions/24072878/start-plotting-graph-from-right-side