我目前正在向影像添加補丁,并希望使用 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()
uj5u.com熱心網友回復:
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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/447237.html
標籤:Python matplotlib 多光标
