我想通过在绘图中单击om来选择点并将点存储在数组中。我想在n次选择后停止选择点,例如按一个键。我怎样才能做到这一点?这是我到目前为止所做的。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(100), 'o', picker=5) # 5 points tolerance
def onpick(event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
points = tuple(zip(xdata[ind], ydata[ind]))
print('onpick points:', points)
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
答案 0 :(得分:1)
要拥有GUI功能,您必须将绘图嵌入GUI框架中;但是,有一种简单的方法可以限制所选项目的数量:
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(100), 'o', picker=5) # 5 points tolerance
points = []
n = 5
def onpick(event):
if len(points) < n:
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
point = tuple(zip(xdata[ind], ydata[ind]))
points.append(point)
print('onpick point:', point)
else:
print('already have {} points'.format(len(points)))
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
onpick point: ((54.0, 0.68482963903475647),)
onpick point: ((54.0, 0.68482963903475647),)
onpick point: ((54.0, 0.68482963903475647),)
onpick point: ((54.0, 0.68482963903475647),)
onpick point: ((54.0, 0.68482963903475647),)
already have 5 points
如果要选择唯一的点,可以使用一个集来存储它们而不是列表。