如何从多个集合在Matplotlib挑
问题描述:
我有几个函数绘制各种收藏到轴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, ...)
我有一个近距离观察到的文件,但目前我没有看到如何实现它一个很好的策略。 任何人都可以提供一些建议吗?(再次,例如真是伪,我完全开放具有相同功能的任何很好的解决方案。)
答
你的伪代码实际上是罚款。这是不可能的,直接添加到艺术家的选择功能。相反,您可以应用一个全局选择器,然后选择要调用的函数。这可以通过预先将地图(艺术家 - >功能)添加到常用字典来控制。根据哪些艺术家触发事件,可能会调用相应的功能。
这里是这样做,密切关注您的示例代码的代码:
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()