This is more of a test suite than an answer to the question.
Here I show that as of Dec 2021, no provided solution actually clears the memory.
We need the following libraries:
import os
import psutil
import numpy
import matplotlib
import matplotlib.pyplot
I create a single function which should clear ALL matplotlib memory:
def MatplotlibClearMemory():
#usedbackend = matplotlib.get_backend()
#matplotlib.use('Cairo')
allfignums = matplotlib.pyplot.get_fignums()
for i in allfignums:
fig = matplotlib.pyplot.figure(i)
fig.clear()
matplotlib.pyplot.close( fig )
#matplotlib.use(usedbackend)
I make a script that creates 100 figures then attempts to delete them all from memory:
#Use TkAgg backend because it works better for some reason:
matplotlib.use('TkAgg')
#Create fake data for our figures:
x = numpy.arange(1000)
#Get system process information for printing memory usage:
process = psutil.Process(os.getpid())
#Check memory usage before we create figures:
print('BeforeFigures: ', process.memory_info().rss) # in bytes
#Make 100 figures, and check memory usage:
for n in range(100):
matplotlib.pyplot.figure()
matplotlib.pyplot.plot(x, x)
print('AfterFigures: ', process.memory_info().rss) # in bytes
#Clear the all the figures and check memory usage:
MatplotlibClearMemory( )
print('AfterDeletion: ', process.memory_info().rss) # in bytes
Which outputs memory remaining:
>>> BeforeFigures: 76083200
>>> AfterFigures: 556888064
>>> AfterDeletion: 335499264
Less than half the memory allocated is cleared (much less if using standard back-end). The only working solutions on this stack overflow page avoid placing multiple figures in memory simultaneously.
plt.close("all")
? I have a script that creates about 60 charts with 3 axes each. I use this at the end of each iteration. Memory consumption seems normal enough. – Mungovan