1

Is there way to save a "Figure" in matplotlib to a file such that if you later wanted to modify the Figure, e.g. change data points, resize the figure, etc. you could load up the file in a new python script and do that?

Right now I save the majority of my plots as Pdfs, but that doesn't allow me to make edits later on. I have to go dig up my old source code and data files. I've lost track of the number of times I've lost the plot-generating code and have to essentially reproduce it all from scratch.

It would be nice if I could just save a plot as a self-contained data file, like Photoshop does with its .psd files, so that I can just load it up directly, type "object.plot()", and not have to worry about external dependencies. Does such a format exist, or if not is there any way I could achieve this?

Paradox
  • 1,935
  • 1
  • 18
  • 31

1 Answers1

3

There is a method of saving the plotted object called pickling. I don't have much experience with it but it should allow you to save the plot to a file using

fig = plt.figure
pl.dump(fig, file('file_name.pickle','w'))

and using

fig = pl.load(open('file_name.pickle','rb'))
fig.show()

to load the saved graph.

Matplotlib warns that, "Pickle files are not designed for long term storage, are unsupported when restoring a pickle saved in another matplotlib version". To be safe, I would just save the array containing the data to the plot to either a .csv or .txt file, and keep this file in a folder with the python file to plot the graph. This way you will always be able to plot your data (no matter the version of matplotlib you are using). You will also have the data and code in the same place, and you can easily read the data from the .csv or .txt file, save it to arrays, and graph it using

file = open("file_name.txt", "r")
if file.mode == 'r':
    data = f.read().splitlines()
    data_array1 = data[0].split(",")
    data_array2 = data[1].split(",")

p, = plt.plot(data_array1, data_array2)

I also suggest uploading your python files along with your .csv or .txt files to Github.

If you would like to read more about pickling in matplotlib I suggest reading the two pages linked below. (1) Pickle figures from matplotlib and (2) https://matplotlib.org/3.1.3/users/prev_whats_new/whats_new_1.2.html#figures-are-picklable

noahjillson
  • 122
  • 7