我有一组分组到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()
答案 0 :(得分: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 ]