Reputation: 4322
I have a script that runs repeatedly and in the process it saves a figure into a folder. After a while I start getting warnings about too many open figures in memory.
I checked other questions on the topic, for example, this one and added plt.close('all')
to my code so now it looks like this:
fig, ax = plt.subplots(figsize=(17,8))
plt.hist(results_df['Diff'], bins=100, density=True, histtype='step')
plt.savefig(f'backtester_results/figures/rf_model_{n_days}_data_and_{lag}_lag.png',
format='png')
plt.close('all')
And yet I keep getting figures piled up in memory and warnings after a while. Where did I go wrong?
Here's the warning:
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.
Upvotes: 0
Views: 2239
Reputation: 170
When reading in the official documentation I would assume that plt.close('all')
only closes the windows without removing the figures (https://matplotlib.org/1.3.0/api/pyplot_api.html#matplotlib.pyplot.close).
As I understand you would need to clear the figure as follows:
fig.clf()
plt.close()
Source: (How can I release memory after creating matplotlib figures)
Upvotes: 1