重新绘制图例当图形关闭时

2024-04-25 01:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

使用matplotlib,我试图在图形关闭时执行回调函数,该函数将重新绘制图形图例。但是,当我打电话的时候斧头图例(),它似乎阻止了正在执行的任何进一步的代码。所以在下面的代码中,“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()

Tags: 函数代码图形closeplotmatplotlibfigplt
1条回答
网友
1楼 · 发布于 2024-04-25 01:44:58

好的,对不起,我已经弄明白了。f.get_axes()返回轴对象的列表。所以后面对ax.legend()的调用不能正常工作。你知道吗

更改为以下行可以解决此问题:

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

我仍然不知道为什么这不会产生某种解释错误。你知道吗

相关问题 更多 >