簡體   English   中英

嘗試加載腌制的 matplotlib 圖時出現 AttributeError

[英]AttributeError while trying to load the pickled matplotlib figure

我使用pickle轉儲matplotlib圖,如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:我的問題似乎與在 SO 提出的這個問題相似。 但是,它是不同的,因為提供的答案不是運行和拋出異常。

在展示您的身材之前,您需要一個畫布管理器。 來自問題Matplotlib 的相同概念:如何顯示已關閉的圖形適用,您可以創建一個函數來制作虛擬圖形並竊取其管理器,如下所示(感謝 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM