Description
Bug summary
It seems that a reference to the figure object is kept in some global state. Executing the code below and closing the figures that pop up results in a linear increase in used memory. This happens with Matplotlib 3.9.1 and later. The latest release that does not exhibit the problem is Matplotlib 3.8.4.
Adding fig.clf()
after the plt.show()
in the code below (clearing the figure after it has been displayed and closed by the user) results in the memory leak being significantly reduced, but not eliminated.
Code for reproduction
import gc
import psutil
import numpy as np
import matplotlib.pyplot as plt
p = psutil.Process()
d = np.linspace(0, 1, 1_000_000)
for i in range(10):
fig, ax = plt.subplots()
ax.plot(d)
plt.show()
gc.collect()
print(p.memory_info().rss)
Actual outcome
185729024
254550016
321282048
389459968
456253440
524554240
592330752
659394560
727457792
794468352
Expected outcome
183324672
251961344
253427712
253464576
253493248
254521344
254529536
253464576
253468672
254476288
Additional information
The leak has been introduced sometime between version 3.8.4 (which gives the expected outcome output above) and version 3.9.1 (which gives the actual outcome output above). It reproduces with Matplotlib version 3.9.4 and 3.10.1
Operating system
Windows
Matplotlib Version
3.9.1
Matplotlib Backend
qtagg
Python version
3.12.9
Jupyter version
No response
Installation
conda