如何在Matplotlib的pick_even中一次只选取一个点

2024-04-20 00:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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))

这很好,给了我一个有点像这样的情节(我之前已经把彩色框和色条放在适当的位置以供参考): scatter plot of points

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

^{pr2}$

**问题是-**如果我点击两个非常接近的点,它就会打印出来

0 [2 3]

或者类似的。我不能再缩小“选取器”的距离,因为这会使鼠标很难精确地处于正确的位置来拾取一个点。在

我想要的是一种方法来限制选择仅是最近的点。 有什么想法吗?在


Tags: andthe脚本eventidgetartistdef
1条回答
网友
1楼 · 发布于 2024-04-20 00:09:26

如果只想打印最近点的索引,则需要找出其中哪一个最接近mouseevent。在

mouseevent在数据坐标中的位置是通过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()

相关问题 更多 >