Skip to content

Fix matplotlib figure memory leak warning in tests#2924

Merged
EwoutH merged 6 commits intomesa:mainfrom
EwoutH:plt_warning
Dec 5, 2025
Merged

Fix matplotlib figure memory leak warning in tests#2924
EwoutH merged 6 commits intomesa:mainfrom
EwoutH:plt_warning

Conversation

@EwoutH
Copy link
Copy Markdown
Member

@EwoutH EwoutH commented Dec 4, 2025

Description

Fixes RuntimeWarning: More than 20 figures have been opened by replacing plt.subplots() with direct Figure() instantiation throughout the visualization codebase.

Problem

The pyplot interface (plt.subplots()) maintains a global registry of all figures, preventing garbage collection and causing memory accumulation. When tests run in sequence, the accumulated figure count exceeds matplotlib's default warning threshold of 20 figures.

Solution

Replace all plt.subplots() calls with direct Figure() instantiation:

# Before
fig, ax = plt.subplots(constrained_layout=True)

# After  
from matplotlib.figure import Figure
fig = Figure(constrained_layout=True)
ax = fig.add_subplot()

Files Changed

  • mesa/visualization/backends/matplotlib_backend.py - Updated initialize_canvas() (1 instance)
  • tests/test_components_matplotlib.py - Updated all test functions (15 instances)

Replace plt.subplots() with Figure() instantiation in test_components_matplotlib.py to prevent memory accumulation and eliminate RuntimeWarning about 20+ open figures. This matches the pattern already used in matplotlib_components.py and allows figures to be garbage collected properly.
@EwoutH EwoutH added the testing Release notes label label Dec 4, 2025
Replace pyplot interface with direct Figure() instantiation in visualization backend and tests. The pyplot interface maintains a global figure registry that prevents garbage collection, causing memory accumulation and triggering RuntimeWarning after 20+ figures are created.

Fixes RuntimeWarning in matplotlib_backend.py:60 and prevents similar warnings in test suite.
@github-actions

This comment was marked as off-topic.

@EwoutH EwoutH merged commit 18f883e into mesa:main Dec 5, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants