I am trying to create a function that will accept a figure handle from a closed matplotlib figure and use that handle to reshow the figure. The below code will do this however the navigation toolbar is still linked to the old (destroyed) figure so plot interactivity is lost. Is there a way of linking the navigation toolbar to the new window so the plot is interactive?
For reference, I have consulted similar questions:
- Matplotlib: how to show a figure that has been closed
- Re-opening closed figure matplotlib
- Matplotlib: re-open a closed figure?
The solution (if it exists) should not require use of a bespoke backend. I am hoping this is possible with whatever backend is default (which changes with different OS). I'm also looking to do this without relying on iPython.
My partially complete solution (which lacks navigation bar interactivity in the reshown figure) is:
import matplotlib.pyplot as plt
def reshow_figure(handle):
figsize = handle.get_size_inches() # get the size of the old figure
fig_new = plt.figure() # make a new figure
new_manager = fig_new.canvas.manager # get the figure manager from the new figure
new_manager.canvas.figure = handle # assign the old figure to the new figure manager
handle.set_canvas(new_manager.canvas) # assign the new canvas to the old figure
handle.set_size_inches(figsize) # restore the figsize
plt.show() # show the resurrected figure
plt.plot([1,2,3,4,5],[1,5,3,4,2])
fig = plt.gcf() # get the figure handle to resurrect the figure later
plt.title('My Figure') # just to check the title copies across
plt.gcf().set_size_inches((10,5)) # set a custom size to test recovery of the figsize
plt.show()
# manually close the figure window
reshow_figure(fig)