Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 关闭地物时重新绘制图例_Python_Matplotlib_Event Handling_Legend - Fatal编程技术网

Python 关闭地物时重新绘制图例

Python 关闭地物时重新绘制图例,python,matplotlib,event-handling,legend,Python,Matplotlib,Event Handling,Legend,使用matplotlib,我试图在地物关闭时执行回调函数,该函数会重新绘制地物图例。然而,当我调用ax.legend()时,它似乎会阻止执行任何进一步的代码。因此,在下面的代码中,永远不会打印“after” 有人能解释一下为什么会这样吗?我是否可以在legend()调用之后但在图形关闭之前运行代码?最终目标是在图形关闭时保存两个不同版本的图形,在保存之间重新绘制图例。谢谢 from __future__ import print_function import matplotlib.pyplot

使用matplotlib,我试图在地物关闭时执行回调函数,该函数会重新绘制地物图例。然而,当我调用ax.legend()时,它似乎会阻止执行任何进一步的代码。因此,在下面的代码中,永远不会打印“after”

有人能解释一下为什么会这样吗?我是否可以在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()

好的,对不起,我已经弄明白了
f.get_axes()
返回轴对象的列表。因此,后面对
ax.legend()
的调用无法正常工作

更改为以下行可修复此问题:

axs = f.get_axes()
for ax in axs:
    leg = ax.legend()
我仍然不确定为什么这不会产生某种解释器错误