1

I am new here and probably this is super obvious, but I don't get it: I wanna save the clicked coordinates (coords) to work with them aferwards, somehow this doesn't work. I am still on Python 2.7 btw.

thanks in advance!

import matplotlib.pyplot as plt

plt.close('all')
coords=[]


# Simple mouse click function to store coordinates
def onclick(event):
    global coords, xi,yi
    xi,yi =event.xdata, event.ydata
    coords.append((xi,yi))
    if len(coords) == 2:
        fig.canvas.mpl_disconnect(cid)
        plt.close(1)



    return coords, xi , yi 




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

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


# Call click func
cid = fig.canvas.mpl_connect('button_press_event', onclick)
print coords


  • What do you see, and what do you expect to see? – noam Jun 12 '20 at 15:41
  • the coords remains empty, albeit I'd like to get the coordinates ( (xi_1, yi_1), (xi_2,yi_2)...) – Christian Wolff Jun 12 '20 at 15:42
  • Possible duplicate of https://stackoverflow.com/questions/25521120/store-mouse-click-event-coordinates-with-matplotlib – bm13563 Jun 12 '20 at 16:17
  • I built it based on that question. But of course it doesn’t work (for me), thus the question in the first place. – Christian Wolff Jun 13 '20 at 07:35
  • @ChristianWolff: I think the problem is that you call mpl_connect after plt.show. The plt.show method will only show what you have configured before, and when you do not configure the click events before showing the plot, it will not be registered. Could approve this in a minimal example right now, also with Python 3.6.5 & Matplotlib 3.3.3: When I put mpl_connect before plt.show, all works fine. No actual problem with global variables here. – asti205 Jan 24 '21 at 12:53

0 Answers0