Python PatchCollection对象上的Pick事件不';t目标点击艺术家

Python PatchCollection对象上的Pick事件不';t目标点击艺术家,python,matplotlib,Python,Matplotlib,我有一个补丁集合,分组成一个补丁集合,然后作为集合添加到轴。已建立拾取事件的回调。当我单击其中一个补丁时,会触发pick事件并调用回调,但事件的艺术家成员是PatchCollection对象,而不是单击的艺术家对象。如何在不必测试每个补丁的情况下确定单击的艺术家 import matplotlib.pyplot as plt from matplotlib.patches import Circle, Rectangle from matplotlib.collections import Pa

我有一个补丁集合,分组成一个补丁集合,然后作为集合添加到轴。已建立拾取事件的回调。当我单击其中一个补丁时,会触发pick事件并调用回调,但事件的艺术家成员是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()

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

如果您对获取单击的集合成员的某些属性感兴趣,可以使用
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     ]

我想我错过了文档中关于将所有补丁均匀化为一个集合的部分。我假设它只是作为一个列表来维护的。不管怎么说,这足以让我知道点击了哪个补丁。