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.
EDIT
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.