Reputation: 51
I am trying to retrieve an array as an output from a matplotlib event:
import numpy as np
import matplotlib.pyplot as plt
def onclick(event):
global points
try:
points = np.append(points,[[event.xdata,event.ydata]],axis=0)
except NameError:
points = np.array([[event.xdata,event.ydata]])
ax.plot(points[:,0],points[:,1],'o')
plt.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((0,10))
ax.set_ylim((0,10))
plt.gcf().canvas.mpl_connect('button_press_event',onclick)
plt.show()
Even tough I have declared "points" to be global,
print(points)
returns a NameError. How can I retrieve "points"? Thank you for any help!!
Upvotes: 3
Views: 4423
Reputation: 53678
You cannot just declare a variable as global
, you have to create it initially. The following code should work as you expect.
import numpy as np
import matplotlib.pyplot as plt
points = []
def onclick(event):
global points
points.append([event.xdata, event.ydata])
ax.plot(event.xdata, event.ydata,'o')
plt.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
plt.show()
Shown below is a plot after I clicked 5 times.
Instead of plotting a new marker every single time you add a point, you could instead modify the plot object you already have. Like below.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
points = []
line, = ax.plot(points, 'o--')
def onclick(event):
global points
points.append([event.xdata, event.ydata])
line.set_data(zip(*points))
plt.draw()
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
plt.show()
This will plot points
once and then everytime the user clicks on the plot it will modify the line
object and re-draw it.
Upvotes: 4