Reputation: 661
I want to select 4 points on a matplotlib
graph and operate on those points as soon as 4 four points are clicked on.
The code below will indeed store the 4 points in the variable points
but does not wait for the four points to be selected. I tried adding a for loop and tried threading here but neither option worked. How can I solve this problem?
fig = plt.figure()
ax = fig.add_subplot(111)
image = np.load('path-to-file.npy')
tfig = ax.imshow(image)
points = []
def onclick(event):
global points
points.append((event.xdata, event.ydata))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
# this line will cause an error because the four points haven't been
# selected yet
firstPoint = points[0]
Upvotes: 2
Views: 39
Reputation: 284602
In this case, you might consider using plt.ginput
instead of "rolling your own".
As a quick example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set(title='Select 4 points')
xy = plt.ginput(4)
x, y = zip(*xy)
ax.fill(x, y, color='lightblue')
ax.plot(x, y, ls='', mfc='red', marker='o')
plt.show()
Upvotes: 1