PyQt4/matplotlib - 如何释放内存? [英] PyQt4 / matplotlib - how to release memory?

查看:114
本文介绍了PyQt4/matplotlib - 如何释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 matplotlib Qt4 后端绘制大量数据.

I am using the matplotlib Qt4 backend to plot a large amount of data.

我的问题是:如何正确关闭matplotlib图形并释放图形占用的内存?figure.close() 不能完成这项工作,关闭绘图窗口也不能.

My question is: how do you properly close the matplotlib figure and release the memory occupied by the plot? figure.close() does not do the job, neither does closing the plot window.

下面的最小工作示例显示了问题:

The minimal working example below shows the problem:

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
from numpy.random import random

class MainWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setGeometry(50, 50, 200, 200)

        self.bPlot = QtGui.QPushButton('Plot',self)
        self.bPlot.resize(75,25)
        self.bPlot.move(25, 25)
        self.bPlot.clicked.connect(self.bPlotHandler)

        self.bClosePlot = QtGui.QPushButton('Close plot',self)
        self.bClosePlot.resize(75,25)
        self.bClosePlot.move(25, 75)
        self.bClosePlot.clicked.connect(self.bClosePlotHandler)

        self.show()

    def bPlotHandler(self):
        self.plotApp=PlotWindow()
        self.plotApp.plot()
        self.plotApp.show()

    def bClosePlotHandler(self):
        self.plotApp.figure.clf()
        self.plotApp=None

class PlotWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(PlotWindow, self).__init__(parent)

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)

    def plot(self):
        data=random(1e5)
        ax = self.figure.add_subplot(111)
        ax.plot(data)
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = MainWindow()
    main.show()

    sys.exit(app.exec_())

推荐答案

也许您可以删除变量?类似的东西

Maybe you may delete the variable? Something like

del self.figure
self.figure = None

这篇关于PyQt4/matplotlib - 如何释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆