12

I'm producing a series of scatterplots, where I keep most of the plot (besides the scatter plot) between each plot. This is done like so: Keeping map overlay between plots in matplotlib

Now I want to add annotation to the plot:

for j in range(len(n)):
   plt.annotate(n[j], xy = (x[j],y[j]), color = "#ecf0f1", fontsize = 4)

However, this annotation stays on the plot between plots. How can I clear the annotation after each figure is saved?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
bjornasm
  • 2,211
  • 7
  • 37
  • 62

1 Answers1

23

You can remove an artist using remove().

ann = plt.annotate (...)
ann.remove()

After removal it may be necessary to redraw the canvas.


Here is a complete example, removing several annotations within an animation:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)
f = lambda x: np.sin(x)
line, = ax.plot(x, f(x))

scat = plt.scatter([], [],  s=20, alpha=1, color="purple", edgecolors='none')
ann_list = []

def animate(j):
    for i, a in enumerate(ann_list):
        a.remove()
    ann_list[:] = []

    n = np.random.rand(5)*6
    scat.set_offsets([(r, f(r)) for r in n])
    for j in range(len(n)):
        ann = plt.annotate("{:.2f}".format(n[j]), xy = (n[j],f(n[j])), color = "purple", fontsize = 12)
        ann_list.append(ann)

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=20, interval=360)
ani.save(__file__+".gif",writer='imagemagick', fps=3)
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thank you. However I got an error: Error: ValueError: list.remove(x): x not in list – bjornasm Feb 18 '17 at 13:24
  • 1
    This error surely comes from the way you used the `artist.remove` functionality. Since I don't know your exact code, I added a working example how you could do it. – ImportanceOfBeingErnest Feb 19 '17 at 20:06
  • You are right. The problem comes when there is no artist to remove. – bjornasm Feb 20 '17 at 13:33
  • 3
    Instead of `.remove()` yo can also use `.set_position((x, y))` to move the annotation around. – Shital Shah Jan 09 '19 at 23:42
  • 1
    @ShitalShah Yes, if you have an annotation that you want to update you may do that. Here, not even the number of annotations is constant, hence I recreate them. – ImportanceOfBeingErnest Jan 09 '19 at 23:45
  • @ImportanceOfBeingErnest Hello, I am trying your code. Can you please tell me what should I put instead of the dots? `ann = plt.annotate (...)` Thanks – leena Jan 14 '21 at 03:53