保存了许多情节后,Matplotlib崩溃了

时间:2013-08-13 16:00:50

标签: 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')                 # 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

当我运行大量结果时,它会在保存几千个图后崩溃。我想我想要做的就是重复我的轴,就像在这个答案:https://stackoverflow.com/a/11688881/354979,但我不明白如何。我该如何优化呢?

2 个答案:

答案 0 :(得分:3)

我会创建一个图并每次清除图形(使用.clf)。

import matplotlib.pyplot as plt

fig = plt.figure()

for result in results:
    fig.clf()   # Clears the current figure
    ...

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

When to use cla(), clf() or close() for clearing a plot in matplotlib?

答案 1 :(得分:0)

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

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')