我将一组补丁分组到一个 PatchCollection 中,然后将其作为一个集合添加到坐标区。建立拾取事件的回调。当我单击其中一个补丁时,将触发 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 ]
