Create a figure that is reference counted
matplotlib, memory-management, python
Solution
If you create the figure without using `plt.figure`, then it should be reference counted as you expect. For example (This is using the non-interactive Agg backend, as well.)
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
# The pylab figure manager will be bypassed in this instance.
# This means that `fig` will be garbage collected as you'd expect.
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
Problem
It seems that the standard way of creating a figure in matplotlib doesn't behave as I'd expect in python: by default calling `fig = matplotlib.figure()` in a loop will hold on to all the figures created, and eventually run out of memory. There are quite a few posts which deal with workarounds, but requiring explicit calls to `matplotlib.pyplot.close(fig)` seems a bit hackish. What I'd like is a simple way to make `fig` reference counted, so I won't have to worry about memory leaks. Is there some way to do this?