2017-10-09 65 views
2

我有一组PatchCollection的修补程序集合,然后将其作为集合添加到轴。挑选事件的回调已建立。当我点击其中一个补丁时,挑选事件触发和回调被调用,但事件的艺术家成员是PatchCollection对象,而不是被点击的艺术家对象。我怎样才能确定点击的艺术家,而无需测试每个补丁?PatchCollection对象上的挑选事件不是针对点击的艺术家

import matplotlib.pyplot as plt 
from matplotlib.patches import Circle, Rectangle 
from matplotlib.collections import PatchCollection 
import numpy as np 

def onclick(event): 
    if event.xdata is not None: 
     print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % 
      ('double' if event.dblclick else 'single', event.button, 
      event.x, event.y, event.xdata, event.ydata)) 

def onpick(event): 
    print("artist=", event.artist) 

    #print("You picked {:s}, which has color={:s} and linewidth={:f}".format(\ 
    # event.artist, event.artist.get_color(), event.artist.get_linewidth())) 

N = 25 

fig = plt.figure(figsize=(5,5)) 
ax = fig.add_subplot(111, aspect='equal') 
ax.set_axis_bgcolor('0.8') 

ax.set_xlim([0,1]) 
ax.set_ylim([0,1]) 

xpts = np.random.rand(N) 
ypts = np.random.rand(N) 
patches = [] 
for x,y in zip(xpts,ypts): 
    circle = Circle((x,y),0.03) 
    patches.append(circle) 

colors = 100 * np.random.rand(len(patches)) 
p = PatchCollection(patches, alpha=.5, picker=2) 
p.set_array(np.array(colors)) 
ax.add_collection(p) 

#cid = fig.canvas.mpl_connect('button_press_event', onclick) 
pid = fig.canvas.mpl_connect('pick_event', onpick) 

plt.show() 

回答

1

一个集合的想法是,没有单一的补丁。否则,它将是现有补丁的简单列表。因此无法从集合中获取单个修补程序,因为它不存在。

如果您有兴趣获得点击收集成员的一些属性,可以使用event.ind。这是被点击的成员的索引。

你可以用这个指数来获得从集合属性的信息:我想我错过了大约均质所有补丁到文档中的部分

def onpick(event): 
    if type(event.artist) == PatchCollection: 
     for i in event.ind: 
      color = event.artist.get_facecolor()[i] 
      print("index: {}, color: {}".format(i,color)) 

将打印像

# index: 23, color: [ 0.279566 0.067836 0.391917 0.5  ] 
+0

一个集合。我认为它只是作为一个列表维护。无论如何,这足以让我知道哪个补丁或补丁被点击了。 – sizzzzlerz

相关问题