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

问题描述 投票:2回答:1

传递传奇文本时,我正试图注释图例。这有效但重复注释,同样当移动图例(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()

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

matplotlib annotations draggable legend
1个回答
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”抓住它,你可能会看到注释在你移动图例时出现和消失。希望没关系。一旦停止移动图例框,它就会停止。

© www.soinside.com 2019 - 2024. All rights reserved.