pythonmatplotlibplotmouse-picking

Waiting for a matplotlib event in python 2.7


i have this code found here on StackOverflow and slighlty modified.

import numpy as np
import matplotlib.pyplot as plt
import time

x = np.arange(-10,10)
y = x**2
x1 = 0

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
plt.show()



def onclick(event):
    global x1, go
    x1 = event.xdata
    print x1
    fig.canvas.mpl_disconnect(cid)


cid = fig.canvas.mpl_connect('button_press_event', onclick)


print x1

I would like to know how to stop/wait the program until I click on the figure.

Because as is written when I call the mpl_connect, I could click on the figure but I immidiatly obtain the output x1 = 0 and not the right value after the click step.

How can I solve it to obtain the right value?

Thank you so much,

Luca


Solution

  • The example provided in the question, is almost okay. The show statement should be after all of the calls to setup the graphics and connect the callback functions. Also, the disconnect is probably not what you intended.

    Here is your code, edited to produce the figure and run the connected function repeatedly.

    #!/usr/bin/python
    
    import numpy as np
    import matplotlib.pyplot as plt
    import time
    
    x = np.arange(-10,10)
    y = x**2
    x1 = 0
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x,y)
    
    def onclick(event):
        global x1, go
        x1 = event.xdata
        print x1
    
    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    
    plt.show()