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', \
    def onPress(self, event):
        if event.inaxes == self.pnt.axes:
            contains, _ = self.pnt.contains(event)
            if contains:
                print(event.xdata, event.ydata)
                x = list(self.pnt.get_xdata())
                y = list(self.pnt.get_ydata())
                self.pnt.set_data(x, y)
                r = random.random()
                g = random.random()
                b = random.random()
                color = (r, g, b)

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)

Leave a Reply

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

You are commenting using your 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