Matplotlib – python – click and drag a Gaussian peak around

# move a guassian curve around
# source multi_guass https://github.com/jithesh82

import matplotlib.pyplot as plt
import numpy as np
import pdb
import sys
sys.path.append('/home/jk/jk/python/xpswork')
from multi_gauss import multiGauss as Gauss

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

press = False

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

def onMove(event):
    global press
    if press == True:
        # only for events inside the axes
        if event.inaxes == pnt.axes:
            x = pnt.get_xdata()
            y = pnt.get_ydata()
            ymax = np.max(y)
            yind = np.argmax(y)
            xmax = x[yind]
            y = y + event.ydata - ymax
            x = x + event.xdata - xmax
            pnt.set_data(x, y)
            print(event.xdata, event.ydata)
            pnt.figure.canvas.draw()

def onRelease(event):
    global press
    press = False
    print(press)
    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', onMove)
pnt.figure.canvas.mpl_connect('button_release_event', onRelease)

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s