6

Is there a way to save the 'state' of a matplotlib figure so that I may open up the plot and interact with it later, e.g. in a new ipython notebook session.

Plotting pdfs and other file formats doesn't quite do justice if you want to edit the figure later.

This would be useful if you want to annotate or rescale a figure later, but you don't necessarily have all the access to the original script/data that produced the figure.

In matlab, which ipython is often reported to try to emulate in many ways, you can simply save the file as a .fig or even a script, like .m (matlab) file! then you reopen your .m or .fig in a later matlab session and edit it.

Can this be done with matplotlib?

user27886
  • 540
  • 12
  • 27
  • 2
    Possible duplicate of [Saving interactive Matplotlib figures](https://stackoverflow.com/questions/4348733/saving-interactive-matplotlib-figures) – Arcturus B Jan 09 '19 at 15:19

1 Answers1

8

You can pickle a figure to disk like this

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

# Plot
fig_object = plt.figure()
x = np.linspace(0,3*np.pi)
y = np.sin(x)
plt.plot(x,y)
# Save to disk
pickle.dump(fig_object,file('sinus.pickle','w'))

And then load it from disk and display:

fig_object = pickle.load(open('sinus.pickle','rb'))
fig_object.show()
Esdes
  • 984
  • 7
  • 12
  • to be clear. what exactly is the fig_object. is that what you get when you do `fig_object= plt.plot(x,y)` – user27886 Mar 20 '15 at 06:20
  • Uhmm... shouldn't `fig_object` be a figure instance? `plot` returns a list and thus `fig_object.show()` will fail. Use `fig_object = plt.gcf()`. – hitzg Mar 20 '15 at 07:57
  • 1
    Updated my answer so it has more details about fig_object – Esdes Mar 20 '15 at 08:05
  • 2
    The saving to disk part should probably look more like `pickle.dump(fig_object, open('sinus.pickle','wb'))`. Can't suggest an edit due to `Suggested edit queue is full`. – nspo Dec 03 '20 at 14:12
  • I can confirm that the correct command is "pickle.dump(fig_object, open('sinus.pickle','wb'))" – Ken Grimes Dec 08 '22 at 17:23