9

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?

1

1 Answer 1

10

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()

5 Comments

to be clear. what exactly is the fig_object. is that what you get when you do fig_object= plt.plot(x,y)
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().
Updated my answer so it has more details about fig_object
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.
I can confirm that the correct command is "pickle.dump(fig_object, open('sinus.pickle','wb'))"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.