编辑:如果我显式改变后端matplotlib从’Qt4Agg’到’Agg’,那么我可以运行我的代码没有错误。我认为这是一个在后端的错误?
我编写一些代码来自动处理相当大量的数据。该代码首先解析我的数据文件并存储所有相关位。然后,我有不同的功能,用于生成每个图表我需要(总共有大约25)。但是,我继续遇到某种内存错误,我认为这是因为Matplotlib / PyPlot没有正确释放内存。
每个绘图函数以pyplot.close(fig)命令结束,由于我只想保存图形,不立即查看它们,因此不包括pyplot.show()。
如果我在解释器中单独运行绘图函数,那么我没有遇到任何问题。但是,如果我做一个单独的函数,它依次调用每个绘制函数,然后我遇到一个“MemoryError:无法为路径分配内存”。
这是一个典型的绘图功能在我的代码看起来像:
def TypicalPlot(self, title=None, comment=False, save=False, show=True):
if title is None:
title = self.dat.title
fig = plt.figure()
host = SubplotHost(fig, 111)
fig.add_subplot(host)
par = host.twinx()
host.set_xlabel("Time (hrs)")
host.set_ylabel("Power (W)")
par.set_ylabel("Temperature (C)")
p1, = host.plot(self.dat.timebase1, self.dat.pwr, 'b,', label="Power",
markevery= self.skip)
p2, = par.plot(self.dat.timebase2, self.dat.Temp1, 'r,',
label="Temp 1", markevery= self.skip)
p3, = par.plot(self.dat.timebase2, self.dat.Temp2, 'g,',
label="Temp 2", markevery= self.skip)
p4, = par.plot(self.dat.timebase2, self.dat.Temp3, 'm,',
label="Temp 3", markevery= self.skip)
host.axis["left"].label.set_color(p1.get_color())
# par.axis["right"].label.set_color(p2.get_color())
#host.legend(loc='lower left')
plt.title(title+" Temperature")
leg=host.legend(loc='lower left',fancybox=True)
#leg.get_frame().set_alpha(0.5)
frame = leg.get_frame()
frame.set_facecolor('0.80')
### make the legend text smaller
for t in leg.get_texts():
t.set_fontsize('small')
### set the legend text color to the same color as the plots for added
### readability
leg.get_texts()[0].set_color(p1.get_color())
leg.get_texts()[1].set_color(p2.get_color())
leg.get_texts()[2].set_color(p3.get_color())
leg.get_texts()[3].set_color(p4.get_color())
if show is True and save is True:
plt.show()
plt.savefig('temp.png')
elif show is True and save is False:
plt.show()
elif show is False and save is True:
plt.savefig('temp.png')
plt.clf()
plt.close(fig)
如果我现在在终端运行
MyClass.TypicalPlot(save=True, show = False)
然后我没有得到任何错误。所有的绘图函数也是如此。
如果我做一个新的功能,这样做:
def saveAllPlots(self, comments = False):
if self.comment is None: comment = False
else: comment = True
self.TypicalPlot(save=True, show=False, comment=comment)
self.AnotherPlot(save=True, show=False)
self.AnotherPlot2(save=True, show=False)
self.AnotherPlot3(save=True, show=False)
...etc, etc, etc
然后它运行大约一半的图,然后我得到“MemoryError:无法分配内存的路径”。