Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fredrick
Created May 26, 2011 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fredrick/993333 to your computer and use it in GitHub Desktop.
Save fredrick/993333 to your computer and use it in GitHub Desktop.
Load time series data via AJAX, graph it
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'query/',
data: ({
type: 'responses',
limit: 5000,
order: 'asc'
}),
dataType: 'json',
success: function(resource) {
var data = [];
for (var i = 0; i < resource.length; i++) {
data.push([resource[i][0], resource[i][1]]);
}
$.plot(
$('#graph'),
[data], {
xaxis: {
mode: 'time'
}
});
},
complete: function(xhr, statusText) {
var response = jQuery.parseJSON(xhr.responseText);
if (xhr.status !== 200) {
alert(response.error);
}
}
});
});
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'query/',
data: ({
type: 'responses',
limit: 15000,
order: 'asc'
}),
dataType: 'json',
success: function(resource) {
// Data
var start = new Date(resource[0][0]),
end = new Date(resource[resource.length - 1][0]),
data = pv.range(resource.length).map(function(i) {
return { x: new Date(resource[i][0]), y: resource[i][1] }
});
// Scales and sizing
var w = 960,
h = 300,
x = pv.Scale.linear(start, end).range(0, w),
y = pv.Scale.linear(0, pv.max(data, function(d) { return d.y })).range(0, h);
// Root panel
var graph = new pv.Panel()
.canvas('graph')
.width(w)
.height(h)
.bottom(20)
.left(30)
.right(20)
.top(5);
// X-axis ticks
graph.add(pv.Rule)
.data(x.ticks())
.visible(function(d) { return d > 0 })
.left(x)
.strokeStyle("#eee")
.add(pv.Rule)
.bottom(-5)
.height(5)
.strokeStyle("#000")
.anchor("bottom").add(pv.Label)
.text(x.tickFormat);
// Y-axis ticks
graph.add(pv.Rule)
.data(y.ticks(5))
.bottom(y)
.strokeStyle(function(d) { d ? "#eee" : "#000"})
.anchor("left").add(pv.Label)
.text(y.tickFormat);
// The line
graph.add(pv.Line)
.data(data)
.interpolate("step-after")
.left(function(d) {return x(d.x)})
.bottom(function(d) {return y(d.y)})
.lineWidth(3);
graph.render();
},
complete: function(xhr, statusText) {
var response = jQuery.parseJSON(xhr.responseText);
if (xhr.status !== 200) {
alert(response.error);
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment