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()
2
  • 1
    What is the problem? What do you mean by "stop selecting"? (You can just stop selecting by literally not selecting any more points) Commented Oct 18, 2017 at 11:05
  • I want to select points for which I want to fit a straight line. Commented Oct 18, 2017 at 11:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If I want to draw a line through the selected points, how can I make Python update the plot?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.