2016-11-18 119 views
0

我有幾個函數繪製各種收藏到軸ax如何從多個集合在Matplotlib挑

def my_scatter(ax, ...): 
    pc = ax.scatter(...) 

def plot(ax, ...): 
    lc = mpl.collections.LineCollection(...) 
    ax.add_collection(lc) 

現在,我想挑選器添加到每個人,從而使最終的每個集合都會調用一個函數加上採集成員的索引。僞編碼,這將實現以下意義的東西:

def example_pick_fct1(idx): 
    ... 

def example_pick_fct2(idx): 
    ... 

def my_scatter(ax, pickfct, ...): 
    pc = ax.scatter(...) 
    pc.add_pickfct(pickfct) 

def my_lines(ax, pickfct, ...): 
    lc = mpl.collections.LineCollection(...) 
    ax.add_collection(lc) 
    lc.add_pickfct(pickfct) 

my_scatter(ax, example_pick_fct1, ...) 
my_scatter(ax, example_pick_fct2, ...) 
my_lines(ax, example_pick_fct2, ...) 

我有一個近距離觀察到的文件,但目前我沒有看到如何實現它一個很好的策略。 任何人都可以提供一些建議嗎?(再次,例如真是僞,我完全開放具有相同功能的任何很好的解決方案。)

回答

0

你的僞代碼實際上是罰款。這是不可能的,直接添加到藝術家的選擇功能。相反,您可以應用一個全局選擇器,然後選擇要調用的函數。這可以通過預先將地圖(藝術家 - >功能)添加到常用字典來控制。根據哪些藝術家觸發事件,可能會調用相應的功能。

這裏是這樣做,密切關注您的示例代碼的代碼:

import matplotlib 
import matplotlib.pyplot as plt 
from matplotlib.colors import colorConverter 
import numpy as np 


a1 = np.random.rand(16,2) 
a2 = np.random.rand(16,2) 
a3 = np.random.rand(5,6,2) 

# Create a pickermap dictionary that stores 
# which function should be called for which artist 
pickermap = {} 
def add_to_picker_map(artist, func): 
    if func != None: 
     pickermap.update({artist:func}) 


def example_pick_fct1(event): 
    print "You clicked example_pick_fct1\n\ton", event.artist 

def example_pick_fct2(event): 
    print "You clicked example_pick_fct2\n\ton", event.artist 

def my_scatter(ax, pickfct=None): 
    pc = ax.scatter(a2[:,0], a2[:,1], picker=5) 
    # add the artist to the pickermap 
    add_to_picker_map(pc, pickfct) 

def my_lines(ax, pickfct=None): 
    lc = matplotlib.collections.LineCollection(a3, picker=5, colors=[colorConverter.to_rgba(i) for i in 'bgrcmyk']) 
    ax.add_collection(lc) 
    # add the artist to the pickermap 
    add_to_picker_map(lc, pickfct) 

def onpick(event): 
    # if the artist that triggered the event is in the pickermap dictionary 
    # call the function associated with that artist 
    if event.artist in pickermap: 
     pickermap[event.artist](event) 


fig, ax = plt.subplots() 
my_scatter(ax, example_pick_fct1) 
# to register the same artist to two picker functions may not make too much sense, but I leave it here as you were asking for it 
my_scatter(ax, example_pick_fct2) 
my_lines (ax, example_pick_fct1) 

#register the event handler 
fig.canvas.mpl_connect('pick_event', onpick) 

plt.show()