我正在使用 matplotlib Qt4 后端来绘制大量数据。
我的问题是:如何正确关闭 matplotlib 图形并释放图形占用的内存?figure.close() 没有完成这项工作,关闭绘图窗口也没有。
下面的最小工作示例显示了问题:
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_())