matplotlib,使用可拖动的图例移动注释

时间:2016-05-24 08:22:35

标签: matplotlib annotations draggable legend

我正在尝试在传递图例文字时注释图例。这有效但重复注释,同样在移动图例时(leg.draggable(state = True)),注释重复,我无法删除它。

以下是重现问题的简化代码:

import numpy as np
import matplotlib.pyplot as plt

#define functions
t = np.arange(0.0, 0.2, 0.1)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

#define graphs
fig, ax = plt.subplots()
line0, = ax.plot(t, y1, label='line0')
line1, = ax.plot(t, y2, label='line1')
leg = ax.legend(loc=2)
leg.draggable(state=True) #enable dragging legend

######################test mouse passing legend text#############
fig.canvas.draw()#draw first to get legend position

legtext = leg.get_texts()
line0 = legtext[0] #text of legend 0
line1 = legtext[1] #text of legend 1

def on_move(event):
    annotations = []

    if line0.contains(event)[0] == True:
        p = leg.get_window_extent()
        annotations.append(ax.annotate('Annotation Text 0', (p.p0[0], p.p1[1]), xycoords='figure pixels', zorder=9))
        # print 'line0', annotations
        fig.canvas.draw()
    elif line1.contains(event)[0] == True:
        p = leg.get_window_extent()
        annotations.append(ax.annotate('Annotation Text 1', (p.p0[0], p.p1[1]), xycoords='figure pixels', zorder=9))
        # print 'line1', annotations
        fig.canvas.draw()
    else:
        # print 'else', annotations
        for note in annotations:
            annotations[note].remove()
            # print 'annotation removed', annotations[note]
            fig.canvas.draw()
fig.canvas.mpl_connect('motion_notify_event', on_move)

plt.show()

当鼠标没有超过图例时,有人可以帮我删除注释吗?谢谢你。

1 个答案:

答案 0 :(得分:0)

您正在创建一个名为annotations的列表,在其中添加或删除元素。您实际上想要做的是修改ax.texts,这是一个包含斧头所有注释的列表。

def on_move(event):

    if line0.contains(event)[0] == True:
        p = leg.get_window_extent()
        ax.annotate('Annotation Text 0', (p.p0[0], p.p1[1]), xycoords='figure pixels', zorder=9)

    elif line1.contains(event)[0] == True:
        p = leg.get_window_extent()
        ax.annotate('Annotation Text 1', (p.p0[0], p.p1[1]), xycoords='figure pixels', zorder=9)

    else:
        ax.texts = []

    fig.canvas.draw()

如果您在左侧抓住图例框,则效果很好,如果在“ line0”或“ line1”处抓住它,则在移动图例时可能会看到注释的出现和消失。希望没关系。一旦停止移动图例框,它也会停止。