Saving interactive Matplotlib figures

I just found out how to do this. The “experimental pickle support” mentioned by @pelson works quite well.

Try this:

# Plot something
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.plot([1,2,3],[10,-10,30])

After your interactive tweaking, save the figure object as a binary file:

import pickle
pickle.dump(fig, open('FigureObject.fig.pickle', 'wb')) # This is for Python 3 - py2 may need `file` instead of `open`

Later, open the figure and the tweaks should be saved and GUI interactivity should be present:

import pickle
figx = pickle.load(open('FigureObject.fig.pickle', 'rb'))

figx.show() # Show the figure, edit it, etc.!

You can even extract the data from the plots:

data = figx.axes[0].lines[0].get_data()

(It works for lines, pcolor & imshow – pcolormesh works with some tricks to reconstruct the flattened data.)

I got the excellent tip from Saving Matplotlib Figures Using Pickle.

Leave a Comment