Select n data points from plot

2024/10/13 2:16:18

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

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.

https://en.xdnf.cn/q/118130.html

Related Q&A

Python azure uploaded file content type changed to application/octet-stream

I am using python Azure sdk. When the file uploaded its content type changed to application/octet-stream. I want to set its default content type like image/png for PNG image.I am using following method…

the dumps method of itsdangerous throws a TypeError

I am following the guide of 『Flask Web Development』. I want to use itsdangerous to generate a token, but some problems occured. Here is my code:def generate_confirmation_token(self, expiration=3600):…

SP 500 List python script crashes

So I have been following a youtube tutorial on Python finance and since Yahoo has now closed its doors to the financial market, it has caused a few dwelling problems. I run this codeimport bs4 as bs im…

sleekxmpp threaded authentication

so... I have a simple chat client like so:class ChatClient(sleekxmpp.ClientXMPP):def __init__(self, jid, password, server):sleekxmpp.ClientXMPP.__init__(self, jid, password, ssl=True)self.add_event_han…

DoxyPy - Member (variable) of namespace is not documented

I get the error message warning: Member constant1 (variable) of namespace <file_name> is not documented. for my doxygen (doxypy) documentation. I have documented the file and all functions and cl…

to_csv append mode is not appending to next new line

I have a csv called test.csv that looks like:accuracy threshold trainingLabels abc 0.506 15000 eew 18.12 15000And then a dataframe called summaryDF that looks like:accu…

Optional keys in string formats using % operator?

Is is possible to have optional keys in string formats using % operator? I’m using the logging API with Python 2.7, so I cant use Advanced String Formatting.My problem is as follow:>>> impor…

HDF5 headers missing in installation of netCDF4 module for Python

I have attempted to install the netCDF4 module several times now and I keep getting the same error:Traceback (most recent call last):File "<string>", line 17, in <module>File &quo…

How to catch network failures while invoking get() method through Selenium and Python?

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this:If I reload the page 99% it will load fine, what is the proper…

Pandas crosstab with own function

I have a function which takes two inputs and returns a float e.g. my_func(A, B) = 0.5. I have a list of possible inputs: x = [A, B, C, D, E, F].I want to produce a square matrix (in this case 6 by 6) …