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

标签 python matplotlib

我正在使用 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/

相关文章:

python - dt.time. Between 返回 pandas 中的空列

python - 如何在 matplotlib 中使用 Font Awesome 符号作为标记

python matplotlib 表格无边框

python - MatPlotLib绕固定轴旋转3D图

C# AES CBC PKCS7 到 Python

python - pip install chatterbot 和 spacy 的错误

python - 渲染默认图像,Django

python - 合并两个嵌套列表并删除重复项

python - matplotlib.pylab.hist 中的 histt​​ype ='bar'/'stepfilled'/'barstacked' 之间有什么区别?

python - 从嵌套字典开发 matplotlib 曲面