How to save Matplotlib figures for further modification using Pickle

When you want to add custom modifications to automatically generated plots without touching your plotting script.

When would this be useful? Imagine you have rather generic scripts to create plots from some simulation data. But now you want also to add the analytical solution for a specific case, e.g. Lamb’s solution for the amplitude of a viscous, oscillating droplet, to your plot or you want to non-dimensionalize your x-axis with some reference value. Instead of modifying (and overburdening) your generic scripts with these specifics, you can dump a Matplotlib figure using Pickle. This file can then be loaded again using Python and give you the dumped object as created previously.

Step-by-step guide

A good description for using Matplotlib in combination with Pickle is given here along with some background information.

Remember to open the Pickle dump in binary mode using the option rb, e.g.

open(my_pickle_dump, 'rb')

If you have followed the description given in the link above, you get an object of type matplotlib.figure.Figure which can then be customized. ☺️

See also