Matplotlib – python – click on two curves and change their colors independently

# click on the 2 curves and change their colors -
# independently

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)

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

fig, ax = plt.subplots()
pnt1, = ax.plot(x, y, 'ro')
pnt2, = ax.plot(x + 1, y, 'ro')

p = []
for pnt in [pnt1, pnt2]:
    I = changeColor(pnt)
    I.connect()
    p.append(I)

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