Last active
February 11, 2021 15:14
-
-
Save demisjohn/883295cdba36acbb71e4 to your computer and use it in GitHub Desktop.
How to use Python's `pickle` to save/load matplotlib Figures to/from a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
To save python objects of any sort, to a file. | |
''' | |
import pickle as pkl | |
pkl.dump( fig, open('FigureObject.pickle', 'wb') ) | |
pkl.dump( fig, open('FigureObject.pickle', 'wb'), fix_imports=True ) # fix_imports makes it py2x compatible - untested | |
''' | |
Load python objects from file | |
''' | |
import pickle as pkl | |
# import other modules needed to work with the figure, such as np, plt etc. | |
figx = pkl.load( open('TLM Curves v3 (H38+others)'+'.pickle', 'rb') ) | |
# display the loaded figure: | |
import matplotlib.pyploy as plt # think this is necessary...haven't tested | |
figx.show() # show the figure, edit it etc.! | |
data = figx.axes[0].lines[0].get_data() # extract data from the figure! works for lines, pcolor & imshow (pcolormesh with some tricks to reconstruct the flattened data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are trying to unpickle the plot in another Jupyter notebook and seeing nothing where you expect the plot to be shown, or are seeing errors like
'NoneType' object has no attribute 'print_figure'
or'NoneType' object has no attribute 'manager'
as you try various combinations ofplt.show()
and.show()
, etc., you'll want to see this StackOverflow answer here. It is because you need another canvas manager before you can show your figure. You can hijack a dummy one to use for your unpickled matplotlib figurex
to display it in a notebook cell, like so: