尝试加载pickle matplotlib图时的AttributeError

时间:2018-03-27 03:24:42

标签: python matplotlib

我使用pickle转储matplotlib数字,如an answer in SO所示。以下是代码段 -

import pickle
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3],[10,-10,30])
pickle.dump(fig, open('fig.pickle', 'wb'))

下面是加载腌制数字的代码片段 -

import pickle
figx = pickle.load(open('fig.pickle', 'rb'))
figx.show()

以上代码显示以下错误 -

AttributeError: 'NoneType' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().

我在Ubuntu 14.04 LTS 64位操作系统上使用Python 3.6.3。以下是我的环境的更多细节 -

> import matplotlib
> matplotlib.__version__
'2.1.0'
> matplotlib.get_backend()
'Qt5Agg'
> import sys
> sys.version_info
sys.version_info(major=3, minor=6, micro=3, releaselevel='final', serial=0)

PS:我的问题与this question asked at SO类似。但是,它是不同的,因为提供的答案没有运行并抛出异常。

1 个答案:

答案 0 :(得分:1)

在显示人物之前,您需要一个画布管理器。适用问题Matplotlib: how to show a figure that has been closed的相同概念,您可以创建一个函数来制作虚拟人物并窃取其管理者,如下所示(版权归Jean-Sébastien所写,上面给出了答案)。

def show_figure(fig):

    # create a dummy figure and use its
    # manager to display "fig"  
    dummy = plt.figure()
    new_manager = dummy.canvas.manager
    new_manager.canvas.figure = fig
    fig.set_canvas(new_manager.canvas)

使用此功能,您可以运行:

show_fig(figx)
figx.show()
相关问题