0

Is it possible to save and load the plot with all its attributes? E.g. pickle the Figure instance and then opening it in another script and redrawing as it was in the original script.

Script1

import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.figure()
pd.to_pickle(fig,'fig.pkl')

Script2

import matplotlib.pyplot as plt
import pandas as pd
fig = pd.read_pickle(fig,'fig.pkl')
# Now plot it so that it looks like in script1
Kosmos
  • 497
  • 3
  • 11

1 Answers1

1

You can use pickle.dump to save:

import matplotlib.pyplot as plt
import pickle
fig, ax = plt.subplots()
pickle.dump(fig, open('fig.pkl', 'wb'))

And pickle.load to recover:

import matplotlib.pyplot as plt
import pickle
fig = pickle.load(open('fig.pkl', 'rb'))
plt.show()

Re: comment about storing figs in a dict

This works on my end -- dump the dict of figure handles:

import matplotlib.pyplot as plt
import pickle

fig1, ax1 = plt.subplots()
ax1.plot([0, 1], [0, 1])

fig2, ax2 = plt.subplots()
ax2.plot([1, 0], [0, 1])

figs = {'fig1': fig1, 'fig2': fig2}
pickle.dump(figs, open('figs.pickle', 'wb'))

Then load the dict and access the desired dict key:

import matplotlib.pyplot as plt
import pickle
figs = pickle.load(open('figs.pickle', 'rb'))  
figs['fig1'] # or figs['fig2']
tdy
  • 36,675
  • 19
  • 86
  • 83
  • 1
    This works perfectly for my prescribed problem. Now say that I nest several figures into a dictionary. Is it possible to load the dictionary and then recover the embedded figures? – Kosmos Mar 10 '21 at 11:08
  • 1
    Hmm if I understand correctly, I edited an example of a figure handle dict. – tdy Mar 10 '21 at 11:28