Matplotlib – python – click-drag to change gaussian peak width

# draw one point using subplot
# click and drag to increase/decrease width of -
# a Gaussian curve

import matplotlib.pyplot as plt
from pdb import set_trace
import numpy as np
import sys
from multi_gauss import multiGauss as Gauss

x = np.linspace(0, 2*3.14, 100)
guess = [100, 3, 0.5]
y = Gauss(x, *guess)

press = False

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

def onMove(event):
    global press
    global guess
    global mouse
    if press == True:
        # only for events inside the axes
        if event.inaxes == pnt.axes:
            print(event.xdata, event.ydata)
            x = list(pnt.get_xdata())
            if mouse < event.xdata:
                guess[2] += 0.01
                guess[2] -= 0.01
            y = Gauss(x, *[guess[0], guess[1],\
            pnt.set_data(x, y)
            #pnt.set_data([event.xdata, event.ydata])

def onRelease(event):
    global press
    global mouse
    press = False
    mouse = None

fig, ax = plt.subplots()
pnt, = ax.plot(x, y, label='click-drag - increase length')
ax.set_title('click-drag - increase length')
ax.plot(x, Gauss(x, *[guess[0] + 50, guess[1], guess[2]]))
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