繁体   English   中英

如何在Matplotlib pick_event中一次仅选择一个点

[英]How to select ONLY one point at a time in Matplotlib pick_event

我有一个Python脚本,它绘制了很多(n)条线,每条线包含10个点,我正在尝试制作它,以便可以单击一条线,它将在其中打印该行的ID和该点的ID线。 到目前为止,我已经知道了:

def onpick(event):
    ind = event.ind
    s = event.artist.get_gid()
    print s, ind

#x and y are n x 10 arrays
#s is the id of the line
for s in range(n):
    ax.plot(x[s,:],y[s,:],'^',color=colors(s),picker=2,gid=str(s))

效果很好,并给了我一点像这样的图(我之前已经将彩色框和颜色栏放在适当的位置以供参考): 点的散点图

我可以单击一个点,它会打印出类似

1 [1]

**问题是这样-**如果我在非常接近的两个点之间单击,它会打印

0 [2 3]

或类似。 我无法再减小“拾取器”的距离,因为这使得很难将鼠标置于正确的正确位置来拾取点。

我想要的是将选秀权限制为仅最接近的一种方法。 有任何想法吗?

如果只想打印最接近点的索引,则需要找出其中哪一个最接近于鼠标事件。

event.mouseevent.xdata在数据坐标中的位置是通过event.mouseevent.xdata (或ydata )获得的。 然后需要计算距离并可以返回最接近点的索引。

import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt

x = np.logspace(1,10,base=1.8)
y = np.random.rayleigh(size=(2,len(x)))

def onpick(event):
    ind = event.ind
    if len(ind) > 1:
        datax,datay = event.artist.get_data()
        datax,datay = [datax[i] for i in ind],[datay[i] for i in ind]
        msx, msy = event.mouseevent.xdata, event.mouseevent.ydata
        dist = np.sqrt((np.array(datax)-msx)**2+(np.array(datay)-msy)**2)
        ind = [ind[np.argmin(dist)]]
    s = event.artist.get_gid()
    print s, ind

colors=["crimson","darkblue"]
fig,ax = plt.subplots()
for s in range(2):
    ax.plot(x,y[s,:],'^',color=colors[s],picker=2,gid=str(s))

fig.canvas.mpl_connect("pick_event", onpick)

plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM