How to show a figure that has been closed in Matplotlib?

When you close a figure in Matplotlib, it's removed from memory and cannot be displayed again using the standard plt.show(). However, you can restore a closed figure by creating a new canvas manager and transferring the figure data.

Understanding the Problem

Once plt.close() is called on a figure, the canvas connection is broken. To display it again, we need to create a new canvas and reassign the figure to it.

Example: Restoring a Closed Figure

Here's how to show a figure that has been closed ?

import numpy as np
import matplotlib.pyplot as plt

# Configure figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create figure and plot data
fig = plt.figure()
x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X values")
plt.ylabel("Y values")

# Close the figure (this breaks the canvas connection)
plt.close(fig)

# Restore the closed figure
new_fig = plt.figure()
new_manager = new_fig.canvas.manager
new_manager.canvas.figure = fig
fig.set_canvas(new_manager.canvas)

# Now the closed figure can be displayed
plt.show()

How It Works

The restoration process involves these key steps ?

  1. Create new figure: plt.figure() creates a new figure with a canvas manager
  2. Get canvas manager: Extract the canvas manager from the new figure
  3. Reassign figure: Set the closed figure as the canvas figure
  4. Set canvas: Connect the closed figure to the new canvas

Alternative Approach: Store Figure Reference

A better practice is to avoid closing important figures or store references before closing ?

import numpy as np
import matplotlib.pyplot as plt

# Create and store figure reference
x = np.linspace(0, 2*np.pi, 100)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Cosine Wave")

# Store the figure before any potential closing
stored_fig = fig

# Even if accidentally closed, we can recreate from stored reference
plt.close(fig)

# Display the stored figure using the canvas manager technique
new_fig = plt.figure()
new_manager = new_fig.canvas.manager
new_manager.canvas.figure = stored_fig
stored_fig.set_canvas(new_manager.canvas)

plt.show()

Key Points

  • Once closed, figures lose their canvas connection
  • Canvas manager reassignment restores the display capability
  • The original figure data remains intact after closing
  • This technique works for any figure that hasn't been garbage collected

Conclusion

Use canvas manager reassignment to restore closed figures in Matplotlib. However, it's better practice to avoid closing important figures or maintain references before closing them.

Updated on: 2026-03-25T23:53:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements