How do I close all the open pyplot windows (Matplotlib)?

When working with Matplotlib, you might need to close pyplot windows to free up memory or prevent too many windows from accumulating. Python provides several methods using plt.close() to handle this.

Different Ways to Close Pyplot Windows

Here are the various methods to close matplotlib figure windows ?

  • plt.close() − Closes the current figure
  • plt.close(fig) − Closes a specific Figure instance
  • plt.close(num) − Closes the figure with number=num
  • plt.close(name) − Closes the figure with that label
  • plt.close('all') − Closes all figure windows

Example: Closing Current Figure

This example shows how to close the current figure window ?

import matplotlib.pyplot as plt
import numpy as np

# Create a simple plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure()
plt.plot(x, y)
plt.title("Sine Wave")

# Display the plot
plt.show()

# Close the current figure
plt.close()
print("Current figure closed")
Current figure closed

Example: Closing All Figures

When you have multiple plots open, use plt.close('all') to close them all at once ?

import matplotlib.pyplot as plt
import numpy as np

# Create multiple figures
for i in range(3):
    plt.figure(i+1)
    x = np.linspace(0, 10, 50)
    y = np.sin(x + i)
    plt.plot(x, y)
    plt.title(f"Plot {i+1}")

print(f"Number of figures before closing: {len(plt.get_fignums())}")

# Close all figures
plt.close('all')
print(f"Number of figures after closing: {len(plt.get_fignums())}")
Number of figures before closing: 3
Number of figures after closing: 0

Example: Closing Specific Figures

You can close specific figures by their number or reference ?

import matplotlib.pyplot as plt
import numpy as np

# Create numbered figures
fig1 = plt.figure(1)
fig2 = plt.figure(2)
fig3 = plt.figure(3)

print(f"Open figures: {plt.get_fignums()}")

# Close figure 2 by number
plt.close(2)
print(f"After closing figure 2: {plt.get_fignums()}")

# Close figure 1 by reference
plt.close(fig1)
print(f"After closing figure 1: {plt.get_fignums()}")
Open figures: [1, 2, 3]
After closing figure 2: [1, 3]
After closing figure 1: [3]

Key Points

  • Always close figures when done to prevent memory issues
  • Use plt.close('all') in scripts to ensure clean slate
  • plt.show() must be called before plt.close() to display the plot
  • plt.get_fignums() helps track open figure numbers

Conclusion

Use plt.close() to close the current figure, or plt.close('all') to close all figures at once. This prevents memory buildup and keeps your matplotlib environment clean.

Updated on: 2026-03-25T20:03:08+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements