从for循环中删除注释

时间:2018-08-31 08:49:20

标签: python python-2.7 matplotlib annotations

问题在于<div id="div2"> ... </div> 不会删除添加到分散点的注释。

但是aux1.remove()确实删除了分散点。因此,当我不断添加/删除新点时,最终会得到很多注释。

aux.remove()

1 个答案:

答案 0 :(得分:0)

问题在于注释的创建在for循环内。当您执行aux1.remove()时,仅删除轴上的最后一个注释。

一种解决方案是将aux1放入列表中,在for循环完成之后,遍历该列表并删除注释:

aux = plt.scatter(obj_dy[:], obj_dx[:], color='green')

aux1_list = [] # empty list that the annotation will go in

for k in range(len(obj_index)):
    aux1 = plt.annotate(str(obj_index[k]), xy = (obj_dy[k], obj_dx[k]))
    aux1_list.append(aux1)

plt.pause(0.1)
aux.remove() # remove scatter points

# remove annotations
for ann in aux1_list:
    ann.remove()

plt.pause(0.01) 
plt.show()

无需将注释存储在列表中的另一种方法是遍历axes子级,检查它们是否为注释,如果是,则删除:

for child in plt.gca().get_children():
    if isinstance(child, matplotlib.text.Annotation):
        child.remove()
相关问题