In matplotlib, if you want to alternate between two images while preserving the current view (location and zoom) as defined by user interaction (e.g., panning or zooming with the mouse), you can achieve this by:
Here’s how you can do it without hardcoding the view in your script, so it respects the user's manual adjustments:
pythonimport numpy as np import matplotlib.pyplot as plt # Create two random images image1 = np.random.rand(100, 100) image2 = np.random.rand(100, 100) fig, ax = plt.subplots() ax.imshow(image1, cmap='viridis') plt.title("Press '1' for Image 1, '2' for Image 2") current_image = image1 def on_key(event): global current_image # Save current view xlim = ax.get_xlim() ylim = ax.get_ylim() if event.key == '1': current_image = image1 elif event.key == '2': current_image = image2 else: return # Update image data ax.clear() ax.imshow(current_image, cmap='viridis') ax.set_title(f"Image: {event.key}") # Restore view ax.set_xlim(xlim) ax.set_ylim(ylim) fig.canvas.draw() fig.canvas.mpl_connect('key_press_event', on_key) plt.show()
ax.get_xlim() and ax.get_ylim() capture the current view (zoom/pan) before switching.ax.set_xlim() and ax.set_ylim() restore the view after updating the image.'1' or '2') triggers the switch.imshow, pcolormesh).Qt5Agg, TkAgg), this will work as expected.Vibe can make mistakes. Check answers. Learn more