我今天发现了一个警告。如果你有一个多次调用一个情节的函数你最好使用plt.close(fig)而不是fig.clf()不知何故第一个不会在内存中累积。 简而言之,如果内存是一个问题,请使用plt.close(图)(虽然看起来有更好的方法,但请注意相关链接的评论结尾)。
因此以下脚本将生成一个空列表:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
而这个将产生一个包含五个数字的列表。
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
从上面的文档中我不清楚关闭一个数字和关闭一个窗口有什么区别。 也许这会澄清。
如果你想尝试一个完整的脚本,你有:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
如果内存是一个问题,有人已经在SO中找到了解决方法,请参阅:创建一个引用计数的数字