2017-08-10 53 views
0

我正在做一个散点图,我想单击各个点来做某件事。这就像现有的示例代码。Matplotlib从多个系列中挑选事件

https://matplotlib.org/examples/event_handling/pick_event_demo.html

我已经实现了on_pick方法

def on_pick(event): 
    ind = event.ind 
    for i in ind: 
     ...do something here with blue or red data... 

但是,我坚持,因为我把多个系列(红色和蓝色)在同一个情节

fig, ax = plt.subplots() 
ax.set_title('click on a point...') 
line, = ax.plot(red_xs, red_ys, 'o', picker=5, color='red') 
line, = ax.plot(blue_xs, blue_ys, 'o', picker=5, color='blue') 

事件.ind是整数的集合。他们是一系列的索引。但是,似乎没有办法确定它们是哪个系列的索引。

必须有办法做到这一点。有谁知道这个诀窍?

谢谢 彼得

回答

1

pick_event_demo您链接到实际上可以告诉你如何知道哪条线是哪个。它说

thisline = event.artist 
xdata = thisline.get_xdata() 
ydata = thisline.get_ydata() 
ind = event.ind 

所以ind意愿指数无论thisline是。

为了给出一个更彻底的例子

line1, = ax.plot(self.red['False'], self.red['True'], 'o', picker=5, color='red') 
line2, = ax.plot(self.blue['False'], self.blue['True'], 'o', picker=5, color='blue') 

dic = {line1 : self.red, line2 : self.blue} 

def on_pick(self,event): 
    series = dic[event.artist] 
    # do something with series 
    for i in event.ind: 
     print(series[i]) 


fig.canvas.mpl_connect('pick_event', on_pick) 
+0

谢谢IOBE。我想我的问题并不清楚。我需要附加额外的元数据到事件,在我的情况下,如果熊猫数据框产生的X和Y的。我找到了一种方法来做到这一点。也许你知道更好的方法。 – user1902291

+0

如果您的解决方案正常工作,那很好。我的观点是,你已经在'on_pick'函数内有'xdata'和'ydata'的数据。相反,如果您需要原始数据,则可以使用艺术家与原始数据的简单映射。我更新了答案,以表明如何做到这一点。 – ImportanceOfBeingErnest

0

这里是我找到了解决办法。它看起来笨重,但也许它是最好的。

通过编写“自定义选取器”,可以将元数据添加到事件中。在这里我想补充“IND”和“系列”

def picker(self,line,mouseevent,series): 
    if mouseevent.xdata is None: 
     return False, dict() 
    xdata = line.get_xdata() 
    ydata = line.get_ydata() 
    maxd = 0.05 
    d = np.sqrt((xdata - mouseevent.xdata) ** 2. + (ydata - mouseevent.ydata) ** 2.) 

    ind = np.nonzero(np.less_equal(d, maxd)) 
    if len(ind): 
     props = dict(ind=ind, series=series) 
     return True, props 
    else: 
     return False, dict() 

一个人可以再附上不同的“自定义选择器”以每个散点图

line, = ax.plot(self.red['False'], self.red['True'], 'o', picker=lambda line,mouseevent: self.picker(line,mouseevent,self.red), color='red') 
    line, = ax.plot(self.blue['False'], self.blue['True'], 'o', picker=lambda line,mouseevent: self.picker(line,mouseevent,self.blue), color='blue') 

然后在on_pick拉动元关()功能

fig.canvas.mpl_connect('pick_event', lambda e: self.on_pick(e)) 

... 

def on_pick(self,event): 
    for i in event.ind: 
     for j in i: 
      series = event.series 
      ...do something with item j of series...