Pickle/Unpickle 并显示 Matplotlib 图

问题描述 投票:0回答:2

我也遇到了在 Python 3.7 和 Matplotlib 3.1.3 中酸洗然后取消拾取并显示 Matplotlib 图形的问题。

我将我的数字保存为(简化代码):

fig, ax = plt.subplots()
fig.show() #works fine
list_figs.append(fig)
output = {
    "figures": list_figs
}
with open( f"mPair.pkl", "wb" ) as f:
    pickle.dump( output, f )
res = pickle.load( open( f"mPair.pkl", "rb" ) )
res["figures"][0].show() #does not work

如果我直接显示该图,代码工作正常,但在酸洗/取消酸洗后我得到:

Traceback (most recent call last):
  File "/Users/xx/opt/anaconda3/envs/nengo3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-4759ba430504>", line 1, in <module>
    res1[ "fig_post" ].show()
  File "/Users/xx/opt/anaconda3/envs/nengo3/lib/python3.7/site-packages/matplotlib/figure.py", line 438, in show
    "created by pyplot.figure()." % err)
AttributeError: 'NoneType' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()
python matplotlib pickle
2个回答
1
投票

如果您不显示该图并在显示之前保存到pickle,即如果您运行此命令,会发生什么:

fig, ax = plt.subplots()
#fig.show() #works fine
list_figs.append(fig)
output = {
    "figures": list_figs
}
with open( f"mPair.pkl", "wb" ) as f:
    pickle.dump( output, f )
res = pickle.load( open( f"mPair.pkl", "rb" ) )
res["figures"][0].show() #does it work?

0
投票

我正在处理同样的问题。我使用 pickleback 能够从交互式窗口保存图形。使用 pickle 再次加载图形后,我首先很难显示它。我尝试了this SO answer中描述的虚拟方法,但随后该图将无法交互。我发现解决方案是为该图形创建一个新的图形管理器,然后注册它。我使用 pyplot 提供的后端,使用

plt._get_backend_mod()
设置为默认值。我创建了以下显示腌制图形的函数。

def show_fig_from_pickle(pickle_file, block_show=True):
    import pickle
    from matplotlib import _pylab_helpers
    import matplotlib.pyplot as plt
    with open(pickle_file, 'rb') as f:
        fig = pickle.load(f)
    
    # make sure plt has set a backend and get it
    bem = plt._get_backend_mod()
    # create a new figure manager for our figure
    mgr = bem.new_figure_manager_given_figure(num=fig.number, figure=fig)
    # set the new figure manager as active
    _pylab_helpers.Gcf.set_active(mgr)

    plt.show(block=block_show)
    return fig
© www.soinside.com 2019 - 2024. All rights reserved.