I am using the matplotlib Qt4 backend to plot a large amount of data.
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_())