将标签添加到图例以进行matplotlib注释

时间:2018-08-31 04:21:01

标签: python matplotlib legend

我正在“注释”某种颜色的许多箭头,以向图中添加数据(发生事件的地方)。 (example code)。有没有办法将其添加到图例?一个答案可能是添加它们manually,如我在下面的代码中所示,但是我想它永远是最后的选择。什么是“正确”的方法? (在图例中还带有小箭头标记的奖励)

这里是一个示例,但实际上,该示例是为了易于使用,问题在于如何为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()

0 个答案:

没有答案