2017-12-18 111 views
0

我的图中有很少的注释是用鼠标点击激活的。我想更新一个特定的注释。但是,注释覆盖了较早的注释。如何清除旧的特定/特定注释并用新值更新,以使其看起来干净。更新matplotlib中的特定注释

from matplotlib import pyplot as plt 

fig, ax = plt.subplots() 
x=1 

def annotate(): 
    global x  
    if x==1:   
     x=-1 
    else: 
     x=1 
    ax.annotate(x, (0.5,0.5), textcoords='data', size=10) 
    ax.annotate('Other annotation', (0.5,0.4), textcoords='data', size=10) 

def onclick(event):  
    annotate() 
    fig.canvas.draw() 

cid = fig.canvas.mpl_connect('button_press_event',onclick) 

回答

1

您可以先创建注释对象,然后更新文本作为annotate()函数的一部分。这可以通过注释对象上的Text Class的set_text()方法完成。 (因为matplotlib.text.Annotation类是基于matplotlib.text.Text类)

这里是如何完成这件事:

from matplotlib import pyplot as plt 

fig, ax = plt.subplots() 
x=1 
annotation = ax.annotate('', (0.5,0.5), textcoords='data', size=10) # empty annotate object 
other_annotation = ax.annotate('Other annotation', (0.5,0.4), textcoords='data', size=10) # other annotate 

def annotate(): 
    global x 
    if x==1: 
     x=-1 
    else: 
     x=1 
    annotation.set_text(x) 


def onclick(event): 
    annotate() 
    fig.canvas.draw() 

cid = fig.canvas.mpl_connect('button_press_event',onclick) 
plt.show() 
+0

这就是我当时正好在寻找。谢谢。 –