Luca Dalbosco
Luca Dalbosco

Reputation: 9

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

Upvotes: 1

Views: 802

Answers (2)

Salma
Salma

Reputation: 1

Delete fig.canvas.mpl_disconnect(cid) From onclick.

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

Does the connection between the event and the function. Also it should be before plt. show().

Upvotes: 0

DrM
DrM

Reputation: 2515

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()

Upvotes: 1

Related Questions