2017-12-18 110 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

這就是我當時正好在尋找。謝謝。 –