gpt4 book ai didi

python - 获取 matplotlib 图上最近数据点的坐标

转载 作者:行者123 更新时间:2023-12-03 15:10:46 24 4
gpt4 key购买 nike

我正在使用 matplotlibNavigationToolbar2QT .工具栏显示光标的位置。但我希望光标捕捉到最近的数据点(当足够接近时)简单地显示最近数据点的坐标。可以以某种方式安排吗?

最佳答案

如果您正在处理大量点,我建议您使用 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)

我重构了 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

光标位置的交互式显示。
如果您希望在导航工具栏上显示最近点的坐标:
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()

使用事件。
如果你想要另一种交互性,你可以使用事件:
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()

关于python - 获取 matplotlib 图上最近数据点的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60177685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com