Store and reload matplotlib.pyplot object

A small modification to Pelson's answer for people working on a Jupyterhub

Use %matplotlib notebook before loading the pickle. Using %matplotlib inline did not work for me in either jupyterhub or jupyter notebook. and gives a traceback ending in AttributeError: 'module' object has no attribute 'new_figure_manager_given_figure'.

import matplotlib.pyplot as plt
import numpy as np
import pickle

%matplotlib notebook

ax = plt.subplot(111)
x = np.linspace(0, 10)
y = np.exp(x)
plt.plot(x, y)
with open('myplot.pkl','wb') as fid:
    pickle.dump(ax, fid)

Then in a separate session:

import matplotlib.pyplot as plt
import pickle

%matplotlib notebook

with open('myplot.pkl','rb') as fid:
    ax = pickle.load(fid)
plt.show()

As of 1.2 matplotlib ships with experimental pickling support. If you come across any issues with it, please let us know on the mpl mailing list or by opening an issue on github.com/matplotlib/matplotlib

HTH

EDIT: Added a simple example

import matplotlib.pyplot as plt
import numpy as np
import pickle

ax = plt.subplot(111)
x = np.linspace(0, 10)
y = np.exp(x)
plt.plot(x, y)
pickle.dump(ax, file('myplot.pickle', 'w'))

Then in a separate session:

import matplotlib.pyplot as plt
import pickle

ax = pickle.load(file('myplot.pickle'))
plt.show()