Skip to main content
 首页 » 编程设计

python之在 matplotlib 图上选择点之前阻止执行

2025年05月04日8kerrycode

我想在 matplotlib 图形上选择 4 个点,并在单击 4 个四点后立即对这些点进行操作。 下面的代码确实会将 4 个点存储在变量 points 中,但不会等待选择这 4 个点。我尝试添加一个 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 而不是“自己动手”。

举个简单的例子:

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()