尝试加载pickled matplotlib figu时发生AttributeError

2024-06-28 09:28:32 发布

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

我使用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'))

下面是加载pickled图的代码段-

^{pr2}$

以上代码显示以下错误-

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

我在Ubuntu14.04LTS64位操作系统上使用Python3.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)

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


Tags: 代码answerimportinfoanbysomatplotlib
1条回答
网友
1楼 · 发布于 2024-06-28 09:28:32

你需要一个画布管理员才能显示你的身材。问题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)

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

^{pr2}$

相关问题 更多 >