【发布时间】:2018-02-06 14:27:06
【问题描述】:
我使用脚本生成了很多图形,这些图形不显示但存储到硬盘。过了一会儿,我收到了消息
/usr/lib/pymodules/python2.7/matplotlib/pyplot.py:412:RuntimeWarning:已经打开了20多个图。通过 pyplot 接口 (
matplotlib.pyplot.figure) 创建的图形会一直保留到明确关闭,并且可能会消耗太多内存。 (要控制此警告,请参阅 rcParamfigure.max_num_figures)。 max_open_warning, RuntimeWarning)
因此,我尝试在存储后关闭或清除数字。到目前为止,我尝试了以下所有方法,但没有一个有效。我仍然收到上面的消息。
plt.figure().clf()
plt.figure().clear()
plt.clf()
plt.close()
plt.close('all')
plt.close(plt.figure())
此外,我还尝试通过以下方式限制打开数字的数量
plt.rcParams.update({'figure.max_num_figures':1})
下面是一段与上述行为类似的示例代码。我在我尝试过的地方添加了我尝试过的不同选项作为 cmets。
from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))
import matplotlib.pyplot as plt
plt.ioff()
#plt.rcParams.update({'figure.max_num_figures':1})
for i in range(0,30):
fig, ax = plt.subplots()
ax.hist([df])
plt.savefig("/home/userXYZ/Development/pic_test.png")
#plt.figure().clf()
#plt.figure().clear()
#plt.clf()
#plt.close() # results in an error
#plt.close('all') # also error
#plt.close(plt.figure()) # also error
完整地说,这是我在使用plt.close时遇到的错误:
无法调用“事件”命令:应用程序已被销毁 在执行“事件生成 $w ”时 (程序“ttk::ThemeChanged”第 6 行) 从“ttk::ThemeChanged”中调用
【问题讨论】:
-
为了确保你总是在同一个图上工作,只需使用这个
plt.figure(1).clf() -
plt.close(fig) 应该这样做
-
@Julien 这也会产生 RuntimeWarning
-
@Y0da: 结果与上述相同
-
可能duplicate。将图形的创建移出 for 循环,并在每次迭代后使用
plt.clf()清除图形。因此,只会创建和重新填充一个图形。
标签: python python-2.7 matplotlib