简体   繁体   English

"Python plt:关闭或清除数字不起作用"

[英]Python plt: close or clear figure does not work

I generate a lots of figures with a script which I do not display but store to harddrive.我用一个我不显示但存储到硬盘驱动器的脚本生成了很多图形。 After a while I get the message过了一会儿我收到消息

/usr/lib/pymodules/python2.7/matplotlib/pyplot.py:412: RuntimeWarning: More than 20 figures have been opened. /usr/lib/pymodules/python2.7/matplotlib/pyplot.py:412:RuntimeWarning:已打开超过 20 个图形。 Figures created through the pyplot interface ( matplotlib.pyplot.figure ) are retained until explicitly closed and may consume too much memory.通过 pyplot 接口 ( matplotlib.pyplot.figure ) 创建的图形会一直保留到显式关闭,并且可能会消耗太多内存。 (To control this warning, see the rcParam figure.max_num_figures ). (要控制此警告,请参阅 rcParam figure.max_num_figures )。 max_open_warning, RuntimeWarning) max_open_warning,运行时警告)

Thus, I tried to close or clear the figures after storing.因此,我尝试在存储后关闭或清除数字。 So far, I tried all of the followings but no one works.到目前为止,我尝试了以下所有方法,但没有一个有效。 I still get the message from above.我仍然从上面收到消息。

plt.figure().clf()
plt.figure().clear()
plt.clf()
plt.close()
plt.close('all')
plt.close(plt.figure())

And furthermore I tried to restrict the number of open figures by此外,我试图通过以下方式限制开放数字的数量

plt.rcParams.update({'figure.max_num_figures':1})

Here follows a piece of sample code that behaves like described above.下面是一段与上述行为类似的示例代码。 I added the different options I tried as comments at the places I tried them.我在我尝试过的地方添加了我尝试过的不同选项作为评论。

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

To be complete, that is the error I get when using plt.close :完整地说,这是我在使用plt.close时遇到的错误:

can't invoke "event" command: application has been destroyed while executing "event generate $w <>" (procedure "ttk::ThemeChanged" line 6) invoked from within "ttk::ThemeChanged"无法调用“事件”命令:应用程序在执行“事件生成 $w <>”(过程“ttk::ThemeChanged”第 6 行)时被破坏,从“ttk::ThemeChanged”中调用

The correct way to close your figures would be to use plt.close(fig) , as can be seen in the below edit of the code you originally posted. 关闭数字的正确方法是使用plt.close(fig) ,这可以在下面编辑你最初发布的代码中看到。

from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))

import matplotlib.pyplot as plt
plt.ioff()
for i in range(0,30):
    fig, ax = plt.subplots()
    ax.hist(df)        
    name = 'fig'+str(i)+'.png'  # Note that the name should change dynamically
    plt.savefig(name)
    plt.close(fig)              # <-- use this line

The error that you describe at the end of your question suggests to me that your problem is not with matplotlib, but rather with another part of your code (such as ttk ). 您在问题结尾处描述的错误向我表明您的问题不是matplotlib,而是代码的另一部分(例如ttk )。

plt.show() is a blocking function, so in the above code, plt.close() will not execute until the fig windows are closed. plt.show()是一个阻塞函数,因此在上面的代码中,plt.close()将在无效窗口关闭之前执行。 You can use plt.ion() at the beginning of your code to make it non-blocking. 您可以在代码的开头使用plt.ion()使其成为非阻塞。 Even though this has some other implications the fig will be closed. 虽然这有其他一些影响,但无花果将被关闭。

I was still having the same issue on Python 3.9.7, matplotlib 3.5.1, and VS Code (the issue that no combination of plt.close()<\/code> closes the figure).我在 Python 3.9.7、matplotlib 3.5.1 和 VS Code 上仍然遇到同样的问题(没有任何plt.close()<\/code>组合关闭该图的问题)。 I have three loops which the most inner loop plots more than 20 figures.我有三个循环,其中最内层的循环绘制了 20 多个数字。 The solution that is working for me is using agg<\/code> as backend and del someFig<\/code> after plt.close(someFig)<\/code> .对我有用的解决方案是在plt.close(someFig)<\/code>之后使用agg<\/code>作为后端和del someFig<\/code> 。 Subsequently, the order of code would be something like:随后,代码的顺序将类似于:

import matplotlib
matplotlib.use('agg')

import matplotlib.pyplot as plt

someFig = plt.figure()

.
.
.

someFig.savefig('OUTPUT_PATH')
plt.close(someFig) # --> (Note 1)
del someFig

.
.
.

This does not really solve my problem, but it is a work-around to handle the high memory consumption I faced and I do not get any of the error messages as before: 这并没有真正解决我的问题,但它是一个解决我面临的高内存消耗的解决方法,我没有像以前那样得到任何错误消息:

from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))

import matplotlib.pyplot as plt
plt.ioff()
for i in range(0,30):
    plt.close('all')
    fig, ax = plt.subplots()
    ax.hist([df])
    plt.savefig("/home/userXYZ/Development/pic_test.png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM