In Python matplotlib how to alternative between 2 images but keep current view (location and zoom) defined with input device and not code?
Jul 1, 12:54pm
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:
Storing the current axes limits before switching images.
Restoring those limits after updating the image data.
Here’s how you can do it without hardcoding the view in your script, so it respects the user's manual adjustments:
Example Code
python
import 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()
How It Works
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.
The key press event ('1' or '2') triggers the switch.
Notes
This approach preserves the user's manual zoom/pan between switches.
Works for any 2D image (e.g., imshow, pcolormesh).
For interactive backends (e.g., Qt5Agg, TkAgg), this will work as expected.
Jul 1, 12:54pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.