To add a color bar to your matplotlib plot, you can use the plt.colorbar() function. In your case, since you are updating the image dynamically, you should also update the color bar when switching images. Here's how you can modify your code to include a color bar:
pythonimport numpy as np import matplotlib.pyplot as plt # Create random images images = [np.random.rand(100, 100) for _ in range(2)] fig, ax = plt.subplots() im = ax.imshow(images[0]) plt.title('1') cbar = plt.colorbar(im, ax=ax) # Add color bar def on_key(event): # Save current view xlim = ax.get_xlim() ylim = ax.get_ylim() try: digit = int(event.key) # Do not use *0*, could be interpreted as 10. imageIndex = min(max(digit - 1, 0), len(images) - 1) current_image = images[imageIndex] except ValueError: return # Update image data, despite being opaque, necessary for switching multiple times ax.clear() im = ax.imshow(current_image) ax.set_title(str(digit)) # Update color bar cbar.update_normal(im) # Restore view, is necessary ax.set_xlim(xlim) ax.set_ylim(ylim) fig.canvas.draw() fig.canvas.mpl_connect('key_press_event', on_key) plt.show()
cbar = plt.colorbar(im, ax=ax) after the first imshow to create the color bar.on_key function, after updating the image with im = ax.imshow(current_image), the color bar is updated using cbar.update_normal(im).This ensures that the color bar is displayed and updated correctly when switching between images.
Vibe can make mistakes. Check answers. Learn more