Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

python - AttributeError while trying to load the pickled matplotlib figure

I used pickle to dump matplotlib figure as shown in an answer in SO. Below is the code snippet-

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

Below is the code snippet to load the pickled figure-

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

The above code shows following error-

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

I am using Python 3.6.3 on Ubuntu 14.04 LTS 64 Bit OS. Below are the more details of my environment-

> 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: My questions seem similar to this question asked at SO. However, it is different since the provided answer is not running and throwing exceptions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need a canvas manager before you can show your figure. The same concept from question Matplotlib: how to show a figure that has been closed applies, you can create a function to make a dummy figure and steal its manager, as below (credit to Jean-Sébastien who wrote the answer above).

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)

With this function you can then run:

show_figure(figx)
figx.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...