Reputation: 6328
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.
Upvotes: 6
Views: 7331
Reputation: 21
As pointed out in Nathan Kiners answer, you need a manager. However, you can create a manager from a figure. If you then set the manager to active, plt.show() will work on it.
Here is a function that does this
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
See [pickleback][1] for registering pickle as a way to save figures. [1]: https://pypi.org/project/pickleback/
Upvotes: 1
Reputation: 29
The pyplot figure manager is needed to display the plot. You can create an instance and use the imported figure by doing this:
plt.new_figure_manager(1).canvas.figure = figx
Upvotes: -1
Reputation: 403
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()
Upvotes: 21