Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Flushing all current figures in matplotlib
In matplotlib, you often create multiple figures during data visualization. To flush all current figures and free up memory, use the plt.close('all') method.
Syntax
plt.close('all')
Creating Multiple Figures
Let's first create multiple figures to demonstrate the flushing process ?
import matplotlib.pyplot as plt
import numpy as np
# Configure figure settings
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create first figure
plt.figure("First Figure")
x1 = np.linspace(0, 10, 100)
plt.plot(x1, np.sin(x1), 'b-')
plt.title("Sine Wave")
# Create second figure
plt.figure("Second Figure")
x2 = np.linspace(0, 10, 100)
plt.plot(x2, np.cos(x2), 'r-')
plt.title("Cosine Wave")
print(f"Number of figures before closing: {len(plt.get_fignums())}")
plt.show()
Number of figures before closing: 2
Flushing All Figures
Now let's close all figures using plt.close('all') ?
import matplotlib.pyplot as plt
import numpy as np
# Create multiple figures
plt.figure("Figure 1")
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("Quadratic Growth")
plt.figure("Figure 2")
plt.plot([1, 2, 3], [1, 2, 3])
plt.title("Linear Growth")
print(f"Figures before closing: {plt.get_fignums()}")
# Flush all current figures
plt.close('all')
print(f"Figures after closing: {plt.get_fignums()}")
Figures before closing: [1, 2] Figures after closing: []
Alternative Closing Methods
Matplotlib provides different ways to close figures ?
import matplotlib.pyplot as plt
# Create test figures
fig1 = plt.figure("Test1")
fig2 = plt.figure("Test2")
fig3 = plt.figure("Test3")
print(f"Initial figures: {plt.get_fignums()}")
# Close specific figure
plt.close("Test1")
print(f"After closing Test1: {plt.get_fignums()}")
# Close current figure
plt.close() # Closes fig3 (current)
print(f"After closing current: {plt.get_fignums()}")
# Close all remaining figures
plt.close('all')
print(f"After closing all: {plt.get_fignums()}")
Initial figures: [1, 2, 3] After closing Test1: [2, 3] After closing current: [2] After closing all: []
Comparison
| Method | Description | Use Case |
|---|---|---|
plt.close() |
Closes current figure | Single figure cleanup |
plt.close(fig) |
Closes specific figure | Selective cleanup |
plt.close('all') |
Closes all figures | Complete memory cleanup |
Conclusion
Use plt.close('all') to flush all current matplotlib figures and free up memory. This is especially useful in scripts that generate many plots or in interactive environments.
Advertisements
