Я ищу аннотировать линии, которые нарисованы между двумя сюжетами.
В данный момент я повторно создаю аннотацию, обращаясь к топору, который запустил «motion_notify_event».
Минимальный пример:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
def update_line_annotation(event, line):
x, y = event.xdata, event.ydata
ax = event.inaxes
global annot # in the real use case, annot is stored as class attribute
annot = ax.annotate(
f'{line}',
xy=(x, y),
xytext=(5, 5),
textcoords='offset points',
)
def hover(event):
annot.set_visible(False)
fig.canvas.draw_idle()
for line in cons:
cont, ind = line.contains(event)
if cont:
update_line_annotation(event, line)
annot.set_visible(True)
break
if __name__ == '__main__':
fig, axes = plt.subplots(ncols=2)
annot = axes[0].annotate(
f'',
xy=(0,0),
xytext=(20, 20),
textcoords='offset points',
)
annot.set_visible(False)
cons = []
for a in range(2):
con = ConnectionPatch(
xyA=np.random.randint(0,10,2),
xyB=np.random.randint(0,10,2),
coordsA='data',
coordsB='data',
axesA=axes[0],
axesB=axes[1],
)
cons.append(con)
axes[1].add_artist(con)
fig.canvas.mpl_connect('motion_notify_event', hover)
for ax in axes:
ax.set_ylim(0,9)
ax.set_xlim(0,9)
plt.show()
Есть две проблемы с моим текущим подходом:
У меня есть два возможных решения, для которых я не могу найти необходимую функциональность в matplotlib:
Помощь приветствуется!






Укажите координаты фигуры figure pixels для xycoords аннотации. Затем используйте event.x и event.y вместо xdata и ydata.
Вы также можете использовать plt.annotate вместо осей, поэтому вам вообще не нужно использовать event.inaxes. Так что не имеет значения, вернется ли это None или нет.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
def update_line_annotation(event, line):
x, y = event.x, event.y
global annot # in the real use case, annot is stored as class attribute
annot = plt.annotate(
f'{line}',
xy=(x, y),
xycoords='figure pixels',
xytext=(5, 5),
textcoords='offset points',
)
def hover(event):
annot.set_visible(False)
fig.canvas.draw_idle()
for line in cons:
cont, ind = line.contains(event)
if cont:
update_line_annotation(event, line)
annot.set_visible(True)
break
if __name__ == '__main__':
fig, axes = plt.subplots(ncols=2)
annot = axes[0].annotate(
f'',
xy=(0,0),
xytext=(20, 20),
textcoords='offset points',
)
annot.set_visible(False)
cons = []
for a in range(2):
con = ConnectionPatch(
xyA=np.random.randint(0,10,2),
xyB=np.random.randint(0,10,2),
coordsA='data',
coordsB='data',
axesA=axes[0],
axesB=axes[1],
)
cons.append(con)
axes[1].add_artist(con)
fig.canvas.mpl_connect('motion_notify_event', hover)
for ax in axes:
ax.set_ylim(0,9)
ax.set_xlim(0,9)
plt.show()