Save matplolib figure in Pickle and open it in Jupyter Notebook


Is it possible to dump the matplotlib plot in Pickle using the default figure manager and load it in Jupyter notebook.
Basically I tried now to save a plot by running a .py file

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

x = np.linspace(-np.pi, np.pi)
y = np.cos(x)
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, label=‘cos(x)’)
ax.set_xlabel(‘Time (s)’)

pickle.dump((fig, ax), open(‘myplot.pickle’, ‘wb’))

and then load the produced pickle in a Jupyter Notebook:

import matplotlib.pyplot as plt
import pickle

fig, ax = pickle.load(open(‘myplot.pickle’, ‘rb’))
ax.set_ylabel(‘Voltage (mV)’)

I always get the following message.

AttributeError: 'NoneType' object has no attribute 'new_figure_manager_given_figure'

That code works for me. I suspect your output and input versions of Matplotlib are different - the pickle objects are not portable across version changes of Matplotlib.


Sorry about the delay. I was in vacation. I have the same matplotlib version (3.5.2).
So you did like me?

  1. Create the file by running a python script (.py) that uses the default backend (I am on windows) and save the figure as pickle
  2. Try to load the same pickle in Jupyter notebook (ipynb)

I had the feeling it came from the fact they have different backends but maybe I am wrong…

Thats possible. I didn’t test that.

I’m personally pretty against pickling figures. Usually it’s just as well to save the data and re-plot. However I can see the use if you have made a bunch of manual changes.