Handling Memory Leaks in Matplotlib
Last Updated :
06 Jan, 2025
Matplotlib sometimes lead to memory leaks when generating a large number of plots.
How to manage Memory Leakage in Matplotlib?
1. Close Figures:
- plt.close(): Close the current figure after you are done with it.
- plt.close('all'): Close all open figures.
Using plt.close()
is essential for freeing up memory after you are done with a plot. This function closes the current figure and releases the associated memory resources.
plt.close()
This method prevents the accumilation of unused figures in memory.
2. Clear the Figure:
Clearing figures using plt.clf()
allows you to clear the current figure's contents without closing it entirely. This is useful when you want to reuse the same figure object for different plots.
plt.clf()
This helps maintain lower memory usage by ensuring that only the necessary data remains in memory while preparing for new plots.
We can also use, plt.clf() to clear the current axes contents
3. Implement Garbage Collection
Implementing garbage collection can help manage memory more effectively. By explicitly calling Python’s garbage collector, you can free up unreferenced objects that are no longer needed.
import gc
gc.collect()
It actively reduces memory usage by removing objects that are no longer accessible
4. Save to Memory Instead of Displaying:
If you don't need to display the plots, save them directly to a file or memory buffer
5. Choose the Right Backend
Choosing the right backend can significantly impact memory performance. Some backends are more efficient than others for specific tasks. For instance, using 'Agg' for non-interactive backends may help reduce overhead.
import matplotlib
matplotlib.use('Agg') # Use Agg backend for non-interactive plotting
6. Use Multiprocessing
For heavy plotting tasks, consider using multiprocessing to create plots in separate processes. This can help isolate memory usage and avoid leaks in the main process:
Handling Memory Usage When Creating Multiple Plots in Python
Let’s move forward with the help of a code to clearly see how memory usage changes when creating multiple plots. This code demonstrates the impact of leaving figures open versus properly closing them to manage memory efficiently.
Python
import matplotlib.pyplot as plt
import numpy as np
import psutil
import os
def memory_usage():
"""Check the memory usage of the current process."""
process = psutil.Process(os.getpid())
return process.memory_info().rss / (1024 * 1024) # Memory in MB
print("Memory usage before creating plots (MB):", memory_usage())
for i in range(1000): # Creating 1000 figures
x = np.linspace(0, 10, 100)
y = np.sin(x + i / 100.0)
plt.figure()
plt.plot(x, y)
plt.title(f"Plot {i+1}")
# Not closing the figure, leading to memory accumulation
print("Memory usage after creating plots without closing (MB):", memory_usage())
# Now properly close figures after use
print("\nMemory usage before proper cleanup (MB):", memory_usage())
for i in range(1000): # Creating 1000 figures again
x = np.linspace(0, 10, 100)
y = np.sin(x + i / 100.0)
plt.figure()
plt.plot(x, y)
plt.title(f"Plot {i+1}")
plt.close() # Close the figure to release memory
print("Memory usage after closing figures (MB):", memory_usage())
Output:
Memory usage before creating plots (MB): 114.734375
RuntimeWarning: More than 20 figures have been opened.
- Memory usage after creating plots without closing (MB): 471.96875
- Memory usage before proper cleanup (MB): 471.96875
- Memory usage after closing figures (MB): 843.9921875