在 matplotlib 图上选择点之前阻止执行
Preventing execution until points are selected on matplotlib graph
我想在 matplotlib
图表上 select 4 个点,并在单击 4 个四点后立即对这些点进行操作。
下面的代码确实会将 4 个点存储在变量 points
中,但不会等待这四个点被 selected。我尝试添加一个 for 循环并尝试线程化 here 但两个选项都不起作用。我该如何解决这个问题?
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]
在这种情况下,您可以考虑使用 plt.ginput
而不是 "rolling your own"。
举个简单的例子:
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()
我想在 matplotlib
图表上 select 4 个点,并在单击 4 个四点后立即对这些点进行操作。
下面的代码确实会将 4 个点存储在变量 points
中,但不会等待这四个点被 selected。我尝试添加一个 for 循环并尝试线程化 here 但两个选项都不起作用。我该如何解决这个问题?
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]
在这种情况下,您可以考虑使用 plt.ginput
而不是 "rolling your own"。
举个简单的例子:
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()