2014-08-31 41 views
0

使用matplotlib时,我试图在图形关闭时执行回调函数,该图形重绘图形图例。但是,当我调用ax.legend()时,它似乎阻止正在执行的任何进一步的代码。所以在下面的代码中,“之后”从不打印。关闭图形时重绘图例

有人可以解释为什么这是?我可以在legend()调用之后运行代码,但在数字关闭之前呢?最终目标是在关闭时保存两个不同版本的图形,在保存之间重新绘制图例。谢谢。

from __future__ import print_function 
import matplotlib.pyplot as plt 

def handle_close(evt): 
    f = evt.canvas.figure 
    print('Figure {0} closing'.format(f.get_label())) 
    ax = f.get_axes() 

    print('before') 
    leg = ax.legend() # This line causes a problem 
    print('after') # This line (and later) is not executed 

xs = range(0, 10, 1) 
ys = [x*x for x in xs] 
zs = [3*x for x in xs] 

fig = plt.figure('red and blue') 
ax = fig.add_subplot(111) 

ax.plot(xs, ys, 'b-', label='blue plot') 
ax.plot(xs, zs, 'r-', label='red plot') 

fig.canvas.mpl_connect('close_event', handle_close) 
ax.legend() 
plt.show() 

回答

0

好吧,对不起,我已经想通了。 f.get_axes()返回轴对象的列表。因此,稍后致电ax.legend()的呼叫无法正常工作。

更改为下面几行解决了这个问题:

axs = f.get_axes() 
for ax in axs: 
    leg = ax.legend() 

我仍然不知道为什么,这并没有产生某种解释错误的,但。