Is there a Python equivalent of .fig
file from Matlab? I am looking for the ability to save the figure from Python but as well extract data from a saved figure later and modify figure if needed.

- 5,433
- 5
- 29
- 63
2 Answers
No, Matplotlib has no native figure files. The API method savefig()
only supports rendering the figure in various image file formats.
If you need to save a figure to a file and later restore it, you can use the pickle
module from the standard library. It lets you dump the binary representation of a figure object (or virtually any Python object actually) to a file. You can then "unpickle" the data in the file, possibly inside a different Python session, to get the original figure object back. Pickling and unpickling is not mentioned in the Matplotlib documentation, but appears to be supported unofficially as a number of issues in the Matplotlib GitHub repository attest, for example #10843 and #17201.
To save a (sample) figure to a file named figure.mpl
:
from matplotlib import pyplot
figure = pyplot.figure()
axes = figure.add_subplot()
axes.plot([0, 0], [1, 1])
import pickle
file = open('figure.mpl', 'wb')
pickle.dump(figure, file)
Note that the code does not call pyplot.show()
. Saving the figure after such a call will fail as it is then no longer actively managed by Matplotlib.
To load the figure from the previously saved file:
import pickle
file = open('figure.mpl', 'rb')
figure = pickle.load(file)
figure.show()

- 4,410
- 2
- 23
- 40
Since you require your data to be preserved along with the visualization, you may need to use pickle. If you're not familiar with the module, it is used by python to store python-readable data locally.
https://fredborg-braedstrup.dk/blog/2014/10/10/saving-mpl-figures-using-pickle/

- 196
- 7