Remove annotation while keeping plot
Asked Answered
P

1

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?

Phosphorism answered 18/2, 2017 at 11:26 Comment(0)
H
25

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

Henley answered 18/2, 2017 at 13:17 Comment(6)
Thank you. However I got an error: Error: ValueError: list.remove(x): x not in listPhosphorism
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.Henley
You are right. The problem comes when there is no artist to remove.Phosphorism
Instead of .remove() yo can also use .set_position((x, y)) to move the annotation around.Car
@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.Henley
@Henley Hello, I am trying your code. Can you please tell me what should I put instead of the dots? ann = plt.annotate (...) ThanksSissel

© 2022 - 2024 — McMap. All rights reserved.