【问题标题】:AttributeError while trying to load the pickled matplotlib figure尝试加载腌制的 matplotlib 图时出现 AttributeError
【发布时间】:2018-09-05 07:55:40
【问题描述】:

我使用pickle 转储matplotlib 图如an answer in SO 所示。下面是代码sn-p-

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'))

下面是sn-p加载腌制图的代码-

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。但是,它有所不同,因为提供的答案没有运行并引发异常。

【问题讨论】:

  • @DyZ:请查看更新后的问题。谢谢!
  • 我无法重现您的错误。此外,当我将 figx.show() 替换为 plt.show() 时,我可以加载该图。
  • @TomdeGeus:替换为plt.show() 不会显示任何内容。 figx.show() 显示上面报告的错误。我不知道重现的确切步骤,但它显示在我的机器上。
  • 如何运行这段代码?您使用的是哪个 matplotlib 版本和哪个后端? print(figx)print(figx.canvas) 打印什么?

标签: python matplotlib


【解决方案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_figure(figx)
figx.show()

【讨论】:

  • 超级有帮助。我发现我也可以用这一行替换第二块中的两行 plt.show(show_figure(figx)) ;我在上面打过import matplotlib.pyplot as plt
  • 关于如何修改上述内容以加载 3D 绘图的任何想法?当前代码确实会加载它们,但无法放大或旋转。
猜你喜欢
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 2023-03-12
  • 2017-03-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多