2017-05-02 27 views
0

我有一個Python腳本,繪製了很多(n)行,每個10個點,並且我試圖讓它可以點擊一行,它將打印行的id和行中的點的id。到目前爲止,我得到這個:如何在Matplotlib中一次只選擇一個點pick_event

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

我可以點擊一個點,並將其打印像

1 [1] 

**問題是這樣的 - **,如果我兩個點非常接近它打印

之間點擊
0 [2 3] 

或類似的。我無法進一步降低「選擇器」距離,因爲這使得很難將鼠標放在恰當的位置來選擇一個點。

我想要的是一種限制選擇只有最接近的點。 任何想法?

回答

1

如果您只想打印最近點的索引,則需要找出哪一個最接近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() 
相關問題