Enki
Enki

Reputation: 1

Google Colab: On-click interactive plots not working

I'm trying to use this snippet, which works as intended locally, in Google Colab. The snippet basically set to NaN a pixel value on click. Google Colab does show correctly the image but if I click on a pixel, it doesn't change anything. Any thoughts? Here's the snippet:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output



def interactive_image(image):
    fig, ax = plt.subplots()
    im = ax.imshow(image, cmap='viridis', interpolation='nearest')

    def on_click(event):
        if event.inaxes is not None:
            x, y = int(round(event.xdata)), int(round(event.ydata))
            image[y, x] = np.nan  # Set the clicked pixel to NaN
            im.set_array(image)
            plt.draw()
            clear_output(wait=True)

    fig.canvas.mpl_connect('button_press_event', on_click)
    plt.show()

# Example usage
image_size = 50
image = np.random.rand(image_size, image_size)
interactive_image(image)

I already tried %matplotlib notebook and in that case it doesn't even show the image.

Upvotes: 0

Views: 173

Answers (0)

Related Questions