【问题标题】:Redrawing legend when the figure is closed图关闭时重绘图例
【发布时间】:2014-08-31 13:43:31
【问题描述】:

使用 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()

【问题讨论】:

    标签: python matplotlib event-handling legend


    【解决方案1】:

    好的,对不起,我已经想通了。 f.get_axes() 返回轴对象的列表。所以后来对ax.legend() 的调用无法正常工作。

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

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

    我仍然不确定为什么这没有产生某种解释器错误。

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2011-09-04
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多