0

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 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()
Rob Schneider
  • 165
  • 5
  • 16

1 Answers1

1

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

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.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80