How to add a color bar to the following Python matplotlib?

```python
import 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()
ax.imshow(images[0])
plt.title('1')

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()
ax.imshow(current_image)
ax.set_title(str(digit))

# 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()
```
Jul 1, 1:38pm

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:

python
import 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()

Key Changes:

  1. Initial Color Bar: Added cbar = plt.colorbar(im, ax=ax) after the first imshow to create the color bar.
  2. Update Color Bar: In the 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.

Jul 1, 1:38pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more