Pyg*_*ion 12 python matplotlib
我使用matplotlib带NavigationToolbar2QT。工具栏显示光标的位置。但我希望光标捕捉到最近的数据点(当足够接近时)或者只是显示最近数据点的坐标。可以以某种方式安排吗?
如果您正在处理大量点,我建议您使用CKDtrees:
import matplotlib.pyplot as plt
import numpy as np
import scipy.spatial
points = np.column_stack([np.random.rand(50), np.random.rand(50)])
fig, ax = plt.subplots()
coll = ax.scatter(points[:,0], points[:,1])
ckdtree = scipy.spatial.cKDTree(points)
Run Code Online (Sandbox Code Playgroud)
我kpie's在这里重构了一点答案。一旦ckdtree被创建,就可以立即识别最接近点和各种形式的关于他们的一点点努力的信息:
def closest_point_distance(ckdtree, x, y):
#returns distance to closest point
return ckdtree.query([x, y])[0]
def closest_point_id(ckdtree, x, y):
#returns index of closest point
return ckdtree.query([x, y])[1]
def closest_point_coords(ckdtree, x, y):
# returns coordinates of closest point
return ckdtree.data[closest_point_id(ckdtree, x, y)]
# ckdtree.data is the same as points
Run Code Online (Sandbox Code Playgroud)
光标位置的交互式显示。 如果您希望在导航工具栏上显示最近点的坐标:
def val_shower(ckdtree):
#formatter of coordinates displayed on Navigation Bar
return lambda x, y: '[x = {}, y = {}]'.format(*closest_point_coords(ckdtree, x, y))
plt.gca().format_coord = val_shower(ckdtree)
plt.show()
Run Code Online (Sandbox Code Playgroud)
使用事件。 如果你想要另一种交互性,你可以使用事件:
def onclick(event):
if event.inaxes is not None:
print(closest_point_coords(ckdtree, event.xdata, event.ydata))
fig.canvas.mpl_connect('motion_notify_event', onclick)
plt.show()
Run Code Online (Sandbox Code Playgroud)
以下代码将打印单击时最靠近鼠标的点的坐标。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
fig,ax = plt.subplots()
plt.scatter(x, y)
points = list(zip(x,y))
def distance(a,b):
return(sum([(k[0]-k[1])**2 for k in zip(a,b)])**0.5)
def onclick(event):
dists = [distance([event.xdata, event.ydata],k) for k in points]
print(points[dists.index(min(dists))])
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
Run Code Online (Sandbox Code Playgroud)