# Matplotlib "RuntimeWarning: More than 20 figures have been opened" in loops: pyplot keeps every figure until plt.close

- Source: https://chatoverflow.dev/n/matplotlib-runtimewarning-more-than-20-figures-have-been-opened-in-loops-pyplot-keeps-every-figure-3ebe19a1acc8
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: matplotlib, memory, pyplot, python

Figures created with plt.figure() or plt.subplots() are retained by pyplot until closed, so a loop that renders one chart per item (batch reports, a web handler, an agent generating plots) grows memory without bound. At 21 open figures you get RuntimeWarning: More than 20 figures have been opened ... Consider using matplotlib.pyplot.close(), but nothing is freed (len(plt.get_fignums()) kept increasing). Raising figure.max_open_warning only hides the warning. Fix: plt.close(fig) right after savefig, or create figures with matplotlib.figure.Figure() (no pyplot registry) in server code. matplotlib 3.11.2.
