Matplotlib – python – click-drag and increase/decrease line length

# draw one point using subplot
# click and drag to increase/decrease length of a line

import matplotlib.pyplot as plt
from pdb import set_trace

press = False

def onPress(event):
    global press
    contains, _ = pnt.contains(event)
    # make sure the click is on the object
    if contains:
        press = True

def onMove(event):
    global press
    if press == True:
        # only for events inside the axes
        if event.inaxes == pnt.axes:
            print(event.xdata, event.ydata)
            x = list(pnt.get_xdata())
            y = list(pnt.get_ydata())
            y[1] = event.ydata
            pnt.set_data(x, y)
            #pnt.set_data([event.xdata, event.ydata])

def onRelease(event):
    global press
    press = False

fig, ax = plt.subplots()
pnt, = ax.plot([2, 2],[5, 7], label='click-drag - increase length')
ax.set_title('click-drag - increase length')
ax.plot([1, 1], [5, 20])
pnt.figure.canvas.mpl_connect('button_press_event', onPress)
pnt.figure.canvas.mpl_connect('motion_notify_event', onMove)
pnt.figure.canvas.mpl_connect('button_release_event', onRelease)

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