从for循环中删除注释

问题描述 投票:0回答:1

问题是aux1.remove()不会删除添加到散点的注释。

aux.remove()确实消除了散点。因此,当我不断添加/删除新点时,我会得到很多注释。

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

for k in range(len(obj_index)):
    aux1 = plt.annotate(str(obj_index[k]), xy = (obj_dy[k], obj_dx[k]))
plt.pause(0.1000)
aux.remove()
aux1.remove()
python python-2.7 matplotlib annotations
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.