Fix matplotlib figure memory leak warning in tests#2924
Merged
Conversation
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.
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.
This comment was marked as off-topic.
This comment was marked as off-topic.
EwoutH
commented
Dec 4, 2025
EwoutH
commented
Dec 4, 2025
quaquel
approved these changes
Dec 5, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes
RuntimeWarning: More than 20 figures have been openedby replacingplt.subplots()with directFigure()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 directFigure()instantiation:Files Changed
mesa/visualization/backends/matplotlib_backend.py- Updatedinitialize_canvas()(1 instance)tests/test_components_matplotlib.py- Updated all test functions (15 instances)