Home > Blockchain >  How to delete Poly3DCollection object in matplotlib python3
How to delete Poly3DCollection object in matplotlib python3

Time:03-09

The code below creates and plots three 3d-polygons. In the dictionary polygon_dict, the label for each Poly3DCollection artist is created and saved. The goal is to refer to a particular polygon using its label and then delete it from the plot. My failed attempt to achieve this (it only works for ax.plot() objects) is shown commented at the end. Any help is much appreciated.

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'.

CodePudding user response:

You can remove artists:

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

As polygon P2 is still referenced in your dictionary, it will not be garbage-collected and continue to exist as a Poly3DCollection object. Therefore, it is not substantially different from

....
print(polygon_dict)
polygon_dict["P2"].set_visible(False)
plt.show()
  • Related