Updating dataSet with flot resets data
I've got a flot chart that I want to dynamically update via AJAX.
I can render the chart initially, but whenever I try to update the dataSet and redraw the chart, it resets all my data points:
plot.setData(dataSet);
plot.draw();
I have tried this with several different array setups, and it seems like I am passing it the right data—the chart just doesn't take.
Anyone have any ideas? Thanks!
http://datasift.islsandbox.com/
This example uses WebSockets开发者_JS百科, so a WebKit browser is your best bet for testing.
In your code you have two things with flot setup. On load, you do this:
var plot = $.plot($("#flotchart"), [{
data: [[35, 0]],
bars: {show: true, horizontal: true}
}]);
Then later, you get some new data via AJAX and do this:
var dataSet = [[pacCount, 0]];//pacCount is a number that increments each call
plot.setData(dataSet);
plot.draw();
The thing that's missing is that in your initial call you're using the data format where each series is an object, but then when you call setData
the second time around, you're using the the "series as an array" variation. I'm not exactly sure where, but that is messing up flot. Here's how to fix it in your second call:
var dataSet = [[pacCount, 0]];//pacCount is a number that increments each call
plot.setData([{
data:dataSet,
bars: {show: true, horizontal: true}
}]);
plot.draw();
If you want several series with its labels:
plot.setData([
{
label: 'Hola',
data: data[0],
},
{
label: 'Hola2',
data: data[1]
}
]);
plot.setupGrid();
plot.draw();
Where data can be retrieved from an ajax call in json format.
For example in php:
<?php
$data[] = array(2,4);
$data[] = array(12,6);
$data[] = array(22,8);
$data[] = array(32,2);
$data1[] = array(4,6);
$data1[] = array(14,3);
$data1[] = array(24,9);
$data1[] = array(34,5);
$response[0] = $data;
$response[1] = $data1;
echo json_encode($response);
?>
In any case, the return format value from the server side should be something like this for two series like the example above:
[[[2,4],[12,6],[22,8],[32,2]],[[4,6],[14,3],[24,9],[34,5]]]
If you want to update your plot more than one time you can encapsulate the options variables
var drawcourb = function(){
var options = {
series : {
}
};
var plot = $.plot($("#placeholder"), [ {
label : "balbla",
data : courbData,
otherOption : "value"
} ], options);
return function(courbData){
plot.setdata([{
label : "blabla",
data : courbData,
}]);
plot.draw();
}
}
Then you can call your function update for exemple :
var updateProgressPlot = drawcourb();
updateProgressPlot(newDataSet);
精彩评论