Я «комментирую» множество стрелок определенного цвета, чтобы добавить данные в график (где произошли события). ( пример кода ). Есть ли способ добавить его в легенду? Одним из ответов может быть добавление их вручную , как показано в коде ниже, но я думаю, что это всегда последнее средство. Каков «правильный» способ сделать это? (бонус также за то, что в легенде есть небольшая стрелка)
Вот пример, но на самом деле, пример для простоты использования, вопрос только в том, как добавить метку для line.axes.annotate
Вот код, практически идентичный приведенному в ссылке:
Функция добавления стрелок к
def add_arrow(line, position=None, direction='right', size=15, color=None, length=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
length: the number of points in the graph the arrow will consider, leave None for automatic choice
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if not length:
length = max(1, len(xdata) // 1500)
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + length
else:
end_ind = start_ind - length
if end_ind == len(xdata):
print("skipped arrow, arrow should appear after the line")
else:
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(
arrowstyle="Fancy,head_width=" + str(size / 150), color=color),
size=size
)
Функция, которая его использует
def add_arrows(line, xs, direction='right', size=15, color=None, name=None):
if name:
if color is None:
color = line.get_color()
patch = mpatches.Patch(color=color, label=name, marker="->")
plt.legend(handles=[patch])
for x in xs:
add_arrow(line, x, color=color)
Пример того, что строка
x,y = [i for i in range(10000)], [i for i in range(10000)]
line = plt.plot(x, y, label="class days")[0]
add_arrows(line, (x,y))
plt.show()