I want to select points by clicking om them in a plot and store the point in an array. I want to stop selecting points after n selections, by for example pressing a key. How can I do this? This is what I have so far.
import numpy as np
import matplotlib.pyplot as pltfig = 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 tolerancedef onpick(event):thisline = event.artistxdata = thisline.get_xdata()ydata = thisline.get_ydata()ind = event.indpoints = tuple(zip(xdata[ind], ydata[ind]))print('onpick points:', points)fig.canvas.mpl_connect('pick_event', onpick)plt.show()
To have GUI functionality, you will have to embed the plot in a GUI frame; however, there is a simple way to limit the number of selected items:
import matplotlib
matplotlib.use('TkAgg')import numpy as np
import matplotlib.pyplot as pltfig = 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 tolerancepoints = []
n = 5def onpick(event):if len(points) < n:thisline = event.artistxdata = thisline.get_xdata()ydata = thisline.get_ydata()ind = event.indpoint = 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()
Example output:
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
If you want to select unique points, you can use a set to store them instead of a list.