如何检测轴属于已在 matplotlib 中关闭的窗口 [英] How to detect that an axis belong to a window that has been closed in matplotlib
问题描述
在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, until it is closed, then I open a new figure. Note that the creation of new plots is triggered by an event in another figure.
如果它可以帮助您了解我的工作意图,请参考以下课程:
If it can help you to understand what I am trying to do, here is the class:
class DetailedPlot(object):
def __init__(self, figure):
self.origin_figure = figure
self.axis = None
self.print_figure = None
self.origin_figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
if event.xdata is None or event.ydata is None:
return
r = round(event.xdata - 0.025, 1)
l = round(event.ydata - 0.025, 1)
if self.axis is None or self.axis.belongs_to_a_closed_window():
self.print_figure = plt.figure()
self.axis = self.print_figure.add_subplot(111)
plotting_fcn(self.axis, r, l)
我的目标是找到一个函数,例如belongs_to_a_closed_window
My aim to to find a function such as belongs_to_a_closed_window
推荐答案
为什么不只将回调连接到"close_event"
?您可以将 ax.has_been_closed
标志添加到轴对象或您的类本身.(可能还有比"has_been_closed"标志更干净的解决方案,具体取决于您在做什么...回调函数可以是任何东西.)
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
(下面扩展我的评论)如果OSX后端未正确实现close事件,您还可以执行以下操作:
(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)
这篇关于如何检测轴属于已在 matplotlib 中关闭的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!