Preserve zoom settings in interactive navigation of matplotlib figure
You need to update the image instead of making a new image each time. As an example:
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Buttonclass DummyPlot(object): def __init__(self): self.imsize = (10, 10) self.data = np.random.random(self.imsize) self.fig, self.ax = plt.subplots() self.im = self.ax.imshow(self.data) buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075]) self.button = Button(buttonax, 'Update') self.button.on_clicked(self.update) def update(self, event): self.data += np.random.random(self.imsize) - 0.5 self.im.set_data(self.data) self.im.set_clim([self.data.min(), self.data.max()]) self.fig.canvas.draw() def show(self): plt.show()p = DummyPlot()p.show()
If you want to plot the data for the first time when you hit "update", one work-around is to plot dummy data first and make it invisible.
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Buttonclass DummyPlot(object): def __init__(self): self.imsize = (10, 10) self.data = np.random.random(self.imsize) self.fig, self.ax = plt.subplots() dummy_data = np.zeros(self.imsize) self.im = self.ax.imshow(dummy_data) self.im.set_visible(False) buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075]) self.button = Button(buttonax, 'Update') self.button.on_clicked(self.update) def update(self, event): self.im.set_visible(True) self.data += np.random.random(self.imsize) - 0.5 self.im.set_data(self.data) self.im.set_clim([self.data.min(), self.data.max()]) self.fig.canvas.draw() def show(self): plt.show()p = DummyPlot()p.show()
Alternately, you could just turn auto-scaling off, and create a new image each time. This will be significantly slower, though.
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Buttonclass DummyPlot(object): def __init__(self): self.imsize = (10, 10) self.fig, self.ax = plt.subplots() self.ax.axis([-0.5, self.imsize[1] - 0.5, self.imsize[0] - 0.5, -0.5]) self.ax.set_aspect(1.0) self.ax.autoscale(False) buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075]) self.button = Button(buttonax, 'Update') self.button.on_clicked(self.update) def update(self, event): self.ax.imshow(np.random.random(self.imsize)) self.fig.canvas.draw() def show(self): plt.show()p = DummyPlot()p.show()