Here's a little more detail to go to Captured Answer . When I first read this answer, I skipped the instruction to call clf() instead of creating a new shape. clf() alone does not help if you then go and create another shape.
Here is a trivial example that triggers a warning:
from matplotlib import pyplot as plt, patches import os def main(): path = 'figures' for i in range(21): _fig, ax = plt.subplots() x = range(3*i) y = [n*n for n in x] ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10)) plt.step(x, y, linewidth=2, where='mid') figname = 'fig_{}.png'.format(i) dest = os.path.join(path, figname) plt.savefig(dest)
To avoid a warning, I have to get the subplots() call out of the loop. To see the rectangles, I need to switch clf() to cla() . This clears the axis without removing the axis itself.
from matplotlib import pyplot as plt, patches import os def main(): path = 'figures' _fig, ax = plt.subplots() for i in range(21): x = range(3*i) y = [n*n for n in x] ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10)) plt.step(x, y, linewidth=2, where='mid') figname = 'fig_{}.png'.format(i) dest = os.path.join(path, figname) plt.savefig(dest)
If you generate graphics in batches, you may have to use both cla() and close() . I ran into a problem when a party could have more than 20 stories without complaining, but it would complain after 20 parties. I fixed this using cla() after each plot and close() after each batch.
from matplotlib import pyplot as plt, patches import os def main(): for i in range(21): print('Batch {}'.format(i)) make_plots('figures') print('Done.') def make_plots(path): fig, ax = plt.subplots() for i in range(21): x = range(3 * i) y = [n * n for n in x] ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10)) plt.step(x, y, linewidth=2, where='mid') figname = 'fig_{}.png'.format(i) dest = os.path.join(path, figname) plt.savefig(dest)
I measured performance to see if it was worth reusing the shape in the package, and this small sample program slowed down from 41 to 49 seconds (20% slower) when I just called close() after each plot.