Matplotlib – click and change color randomly

# click and change color randomly

import matplotlib.pyplot as plt
from matplotlib.backend_bases import MouseButton
import random

#plt.ion()

x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

def on_click(event):
    if event.button is MouseButton.LEFT:
        print(event.xdata, event.ydata)
        r = random.random()
        g = random.random()
        b = random.random()
        plt.clf()
        plt.plot(x, y, 'o', color=(r, g, b))
        plt.draw()

plt.connect('button_press_event', on_click)
plt.plot(x,y, 'ro')
plt.show()


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s