简体   繁体   English

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

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

I have a Python script that plots lots (n) of lines, each of 10 points, and I am trying to make it so that I can click on a line and it will print the id of the line and the id of the point in the line. 我有一个Python脚本,它绘制了很多(n)条线,每条线包含10个点,我正在尝试制作它,以便可以单击一条线,它将在其中打印该行的ID和该点的ID线。 So far I have got this: 到目前为止,我已经知道了:

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))

That works fine and gives me a plot a bit like this (I have previously put the coloured boxes and colorbar in place for reference): 效果很好,并给了我一点像这样的图(我之前已经将彩色框和颜色栏放在适当的位置以供参考): 点的散点图

I can click on a point and it prints something like 我可以单击一个点,它会打印出类似

1 [1]

**The problem is this - ** if I click between two points that are very close it prints **问题是这样-**如果我在非常接近的两个点之间单击,它会打印

0 [2 3]

or similar. 或类似。 I can't reduce the "picker" distance any further because that makes it very hard to get the mouse in the exact right position to pick a point. 我无法再减小“拾取器”的距离,因为这使得很难将鼠标置于正确的正确位置来拾取点。

What I would like is a way of limiting the pick to be ONLY the closest point. 我想要的是将选秀权限制为仅最接近的一种方法。 Any ideas? 有任何想法吗?

If you want to print only the index of the closest point, you need to find out which one of those is the closest to the mouseevent. 如果只想打印最接近点的索引,则需要找出其中哪一个最接近于鼠标事件。

The location of the mouseevent in data coordinates is obtained via event.mouseevent.xdata (or ydata ). event.mouseevent.xdata在数据坐标中的位置是通过event.mouseevent.xdata (或ydata )获得的。 Then the distance needs to be calculated and the index of the point which is closest can be returned. 然后需要计算距离并可以返回最接近点的索引。

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