Python Matplotlib在保存多个绘图后崩溃

Python Matplotlib在保存多个绘图后崩溃,python,matplotlib,Python,Matplotlib,我正在绘制并保存数千个文件,以便以后在循环中制作动画,如下所示: import matplotlib.pyplot as plt for result in results: plt.figure() plt.plot(result) # this changes plt.xlabel('xlabel') # this doesn't change plt.ylabel('ylabel')

我正在绘制并保存数千个文件,以便以后在循环中制作动画,如下所示:

import matplotlib.pyplot as plt
for result in results:
    plt.figure()
    plt.plot(result)                     # this changes
    plt.xlabel('xlabel')                 # this doesn't change
    plt.ylabel('ylabel')                 # this doesn't change
    plt.title('title')                   # this changes
    plt.ylim([0,1])                      # this doesn't change
    plt.grid(True)                       # this doesn't change
    plt.savefig(location, bbox_inches=0) # this changes

当我运行这个程序并得到很多结果时,它会在保存了数千个绘图后崩溃。我想我要做的是重复使用我的斧头,就像下面的回答:但我不明白怎么做。如何优化它?

我会创建一个图形,每次都清除该图形(使用
.clf

由于每次调用
plt.figure
都会创建一个新的figure对象,因此内存不足。根据@tcaswell的评论,我认为这将比
.close
更快。这些差异的解释如下:


虽然这个问题很老,但答案是:

import matplotlib.pyplot as plt
fig = plt.figure()
plot = plt.plot(results[0])
title = plt.title('title')

plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.ylim([0,1])
plt.grid(True)

for i in range(1,len(results)):
    plot.set_data(results[i])
    title.set_text('new title')
    plt.savefig(location[i], bbox_inches=0)
plt.close('all')

几周前我遇到了类似的问题。我解决了我的问题,我在子组中创建了绘图,将它们保存到磁盘,从内存中清除,然后继续绘制其余部分。我认为这是因为matplotlib在处理大型或多个绘图时在内存中保存绘图的方式效率低下。不幸的是,图书馆的一个假设是使用的数据应该相对较小。只要我能将绘图保存在内存中,而不是交换到光盘上,我的绘图就可以正常工作。在循环结束时添加一个
plt.close('all')
。这不会加快速度,但会让你的内存不会耗尽。@谢谢你的提示!我不知道
plt.close('all')
方法。fig=plt.figure()之间有什么区别吗;对于结果中的结果:fig.clf()…'和'plt.figure();对于result in results:plt.clf()…'?@Earlbelinger,当您只有一个图形时没有区别。
plt.figure().clf
调用当前图形,而
fig.clf
调用表示我们的图形的命名对象。如果我们有多个图形,则可能不同。
import matplotlib.pyplot as plt
fig = plt.figure()
plot = plt.plot(results[0])
title = plt.title('title')

plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.ylim([0,1])
plt.grid(True)

for i in range(1,len(results)):
    plot.set_data(results[i])
    title.set_text('new title')
    plt.savefig(location[i], bbox_inches=0)
plt.close('all')