带有 matplotlib.pyplot 个补丁的 Pythons mplcursors

Pythons mplcursors with matplotlib.pyplot patches

我目前正在为图像添加补丁,并想用 mplcursors 对其进行注释。

但是,我无法让 mplcursors 有选择地对绘制的补丁做出反应,而不是对整个图像(即每个像素)做出反应: 这是我正在处理的一个最小工作示例,关于如何解决此问题的任何提示?

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

fig, ax = plt.subplots(1,1)
im = np.zeros((300, 300))
imgplot = ax.imshow(im, interpolation = 'none')

rect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')
label = ['a', 'b', 'c', 'd', 'e', 'f']
cursor = mplcursors.cursor(ax.patches, hover = True).connect('add',
    lambda sel: sel.annotation.set(text = label[sel.index]))
ax.add_patch(rect)

plt.show()
如果在将矩形添加到绘图之前创建游标,

ax.patches 仍然是空的。因此,早点调用 ax.add_patch(rect) 会有所帮助。注释函数可以访问所选元素(“艺术家”)的属性,因此您可以添加信息作为标签。由于 mplcursors 似乎不适用于圆形,您可以创建一个正多边形来近似一个。

import matplotlib.pyplot as plt
import numpy as np
import mplcursors
from matplotlib.patches import Rectangle, Polygon

fig, ax = plt.subplots(1, 1)
im = np.zeros((300, 300))
img = ax.imshow(im, interpolation='none')

ax.add_patch(Rectangle((50, 100), 40, 30, linewidth=3, edgecolor='r', facecolor='none', label='first rectangle'))
ax.add_patch(Rectangle((150, 100), 40, 30, linewidth=3, edgecolor='y', facecolor='none', label='second rectangle'))
th = np.linspace(0, 2 * np.pi, 32)
rad, cx, cy = 50, 130, 200
ax.add_patch(Polygon(rad * np.c_[np.cos(th), np.sin(th)] + np.array([cx, cy]), closed=True, linewidth=3, edgecolor='g',
                     facecolor='none', label='a polygon\napproximating a circle'))

cursor = mplcursors.cursor(ax.patches, hover=True)
cursor.connect('add', lambda sel: sel.annotation.set(text=sel.artist.get_label()))

plt.show()