Update a specific annotation in matplotlib

2019-08-16 16:22发布

问题:

I have few annotations in my plot which are activated with mouse click. I want to update one specific annotation. However, the annotation is overriding the earlier annotation. How do I clear the old specific/particular annotation and update with new value so that it looks clean.

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:

You can create the annotation objects before and then update the text as part of your annotate() function. This can be done by set_text() method of Text Class on the annotate object. (because matplotlib.text.Annotation class is based on matplotlib.text.Text class)

Here is how this done:

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()