如何删除 matplotlib 中的 Poly3DCollection 对象 python3

How to delete Poly3DCollection object in matplotlib python3

下面的代码创建并绘制了三个 3d 多边形。在字典 polygon_dict 中,每个 Poly3DCollection 艺术家的标签都已创建并保存。目标是使用其标签引用特定的多边形,然后将其从绘图中删除。我失败的尝试(它仅适用于 ax.plot() 个对象)在最后显示为注释。非常感谢任何帮助。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

polygon_dict = {}
polygon_count = 0

def plot_polygon(vertices):
    global polygon_count
    polygon_count += 1
    polygon_label = 'P' + str(polygon_count)
    polygon_dict[polygon_label] = ax.add_collection3d(Poly3DCollection([vertices]))

[plot_polygon(np.random.rand(3,3)) for i in range(3)]
print(polygon_dict)
plt.show()

# Delete polygon with label 'P2'. The following doesn't work.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# polygon_dict['P2'].pop(0)
# plt.show()
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The resulting plot should not have polygon 'P2'.

你可以remove artists:

...
print(polygon_dict)
polygon_dict["P2"].remove()
plt.show()

由于多边形 P2 仍在您的字典中引用,因此它不会 garbage-collected 并继续作为 Poly3DCollection 对象存在。因此,它与

没有本质区别
....
print(polygon_dict)
polygon_dict["P2"].set_visible(False)
plt.show()