I have a simple application which polls database for data every minute. When new data is fetched, I am updating the graph using ajax. However, whenever I update the graph (re-plot it with new values adde开发者_开发百科d to plot data) the current state of zoom is lost. Before updating the graph, I want to preserve the latest zoom position. After updating the graph, I want to zoom the graph to its saved position. This is important because re-zooming every minute is irritating. Is this possible?
I tried this answer from Ozan and I couldn't get the block for copying the zoom to work so I just used plot.getOptions() and used that to draw the graph. Like this:
var oldOptions = plot.getOptions();
plot = $.plot($("#graph"), data, oldOptions);
This way you can dynamically change your view and the auto-update will update without changing your view.
Here is the answer by Joshua Varner 1
When you get your new data before you re plot get the current zoom and add it to the options on update.
// Get the current zoom
var zoom = plot.getAxes();
// Add the zoom to standard options
var zoomed = {};
$.extend(zoomed,options);
zoomed.xaxis.min = zoom.xaxis.min;
zoomed.xaxis.max = zoom.xaxis.max;
zoomed.yaxis.min = zoom.yaxis.min;
zoomed.yaxis.max = zoom.yaxis.max;
// draw/save the plot
plot = $.plot($("#graph"), d, zoomed);
You should get the information about the state of the current axes, merge it with your initial options and than provide them to the new plot.
// Deep copy of the options object so that we can keep it unchanged
// for when we don't want to preserve the zoom.
var copyOptions = $.extend(true, {}, options);
if (plot != null && preserveZoom) {
// There might be more than one Y axis
var zoomY = plot.getYAxes();
for (var i = 0; i < zoomY.length; i++) {
copyOptions.yaxes[i].min = zoomY[i].min;
copyOptions.yaxes[i].max = zoomY[i].max;
}
// Considering only one X axis, in case of more than one
// you should use the same method as for the Y axis.
copyOptions.xaxis.min = plot.getXAxes()[0].min;
copyOptions.xaxis.max = plot.getXAxes()[0].max;
}
plot = $.plot("#placeholder", data, copyOptions);
精彩评论