Matplotlib – python – click on the curve and change its color randomly

# draw one point using subplot
# click on the curve and change its color

import matplotlib.pyplot as plt
import random
import numpy as np
import pdb

x = np.linspace(0, 2*3.14, 100)
y = np.sin(x)

def onPress(event):
    if event.inaxes == pnt.axes:
        contains, _ = pnt.contains(event)
        if contains:
            #print(True)
            print(event.xdata, event.ydata)
            x = list(pnt.get_xdata())
            y = list(pnt.get_ydata())
            pnt.set_data(x, y)
            #print(dir(pnt))
            r = random.random()
            g = random.random()
            b = random.random()
            color = (r, g, b)
            pnt.set_markerfacecolor(color)
            pnt.set_markeredgecolor(color)
            pnt.figure.canvas.draw()

fig, ax = plt.subplots()
pnt, = ax.plot(x, y, 'ro')
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
#pnt.figure.canvas.mpl_connect('motion_notify_event', onPress)

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