Skip to content Skip to sidebar Skip to footer

How To Detect That An Axis Belong To A Window That Has Been Closed In Matplotlib

In matplotlib, I keep a reference on an axis. I want to open a new figure if the window that contain the axis have been closed. The idea is to keep adding plots on the figure, unti

Solution 1:

Why not just connect a callback to the "close_event"? You could either add a ax.has_been_closed flag to the axes object or your class itself. (There are probably even cleaner solutions than a "has_been_closed" flag, depending on exactly what you're doing... The callback function can be anything.)

import matplotlib.pyplot as plt

def on_close(event):
    event.canvas.figure.axes[0].has_been_closed = True
    print 'Closed Figure'

fig = plt.figure()
ax = fig.add_subplot(111)
ax.has_been_closed = False
ax.plot(range(10))

fig.canvas.mpl_connect('close_event', on_close)

plt.show()

print ax.has_been_closed

Edit: (Expanding on my comment below) If the OSX backend end doesn't properly implement a close event, you could also do something like this:

import matplotlib.pyplot as plt

def has_been_closed(ax):
    fig = ax.figure.canvas.manager
    active_fig_managers = plt._pylab_helpers.Gcf.figs.values()
    return fig not in active_fig_managers

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))

print has_been_closed(ax)

plt.show()

print has_been_closed(ax)

Post a Comment for "How To Detect That An Axis Belong To A Window That Has Been Closed In Matplotlib"