首页 > 解决方案 > 如何在不关闭图形的情况下清除所有子图?

问题描述

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

N = 50

fig = plt.figure()

ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.set_title('Cartesian Plot')

# im = fig.add_subplot(1, 2, 2)
# im.set_title('Image')
# im.axis('off')

plt.ion()
plt.show()

for p in range(10):
    Z = np.random.randint(255, size=(N, N, 3))
    A, B, C = Z[:, 0], Z[:, 1], Z[:, 2]
    ax.scatter(A, B, C, c='r', marker='.')
    # im.imshow(Z)

    plt.draw()
    plt.pause(1)
    plt.cla()

plt.ioff()
plt.close()

我正在尝试绘制图像,并且在修改后一次又一次地绘制笛卡尔图,所以我设置了这个示例。如果您注释掉图像部分,则此代码有效,然后正确清除笛卡尔图。但是,如果您添加图像子图(取消注释im子图)而不是清除和重绘所有子图,它们会相互绘制,这对于笛卡尔空间中的图来说是一个问题。

有人可以帮助我吗?在循环的每次迭代之后,我希望为下一次迭代清除和重绘两个子图,依此类推。

对于我所做的图像,我还希望不显示标记轴的数字,im.axis('off')但这仅适用于第一次迭代,并且设置为默认值。

标签: pythonmatplotlibanimationsubplot

解决方案


尝试使用:

subplot.cla()  # this clears the data but not the axes
subplot.clf()  #  this clears the data and the axes

所以在你的情况下,它将是

ax.cla()

或者

ax.clf()

推荐阅读