python plt 内存_python – Matplotlib和Pyplot.close()不释放内存? – 后端相关的Qt4Agg

博主遇到在使用matplotlib批量生成图表时出现内存错误的问题。虽然每个绘图函数都使用了`pyplot.close(fig)`来关闭图形,但在连续调用多个绘图函数时,仍发生“MemoryError”。通过将后端从'Qt4Agg'更改为'Agg',问题得以解决。这可能是因为'Qt4Agg'后端在内存管理上存在bug。
摘要由CSDN通过智能技术生成

编辑:如果我显式改变后端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:无法分配内存的路径”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值