2017-02-18 99 views

回答

4

您可以使用remove()刪除藝術家。

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

移除之後,可能需要重新繪製畫布。


下面是一個完整的例子,一個動畫中刪除一些註釋:

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

+0

謝謝。然而,我得到一個錯誤: 錯誤:ValueError:list.remove(x):x不在列表中 – bjornasm

+1

此錯誤肯定來自您使用'artist.remove'功能的方式。由於我不知道你的確切代碼,我添加了一個工作示例,你如何做到這一點。 – ImportanceOfBeingErnest

+0

你說得對。問題出現在沒有藝術家去除的時候。 – bjornasm