2017-02-18 28 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