4

I want to create a python script that zooms in and out of matplotlib graphs along the horizontal axis. My plot is a set of horizontal bar graphs.

I also want to make that able to take any generic matplotlib graph.

I do not want to just load an image and zoom into that, I want to zoom into the graph along the horizontal axis. (I know how to do this)

Is there some way I can save and load a created graph as a data file or is there an object I can save and load later?

(typically, I would be creating my graph and then displaying it with the matplotlib plt.show, but the graph creation takes time and I do not want to recreate the graph every time I want to display it)

azazelspeaks
  • 5,727
  • 2
  • 22
  • 39

2 Answers2

5

You can use pickle package for saving your axes and then load it back.

Save your plot into a pickle file:

import pickle
import matplotlib.pyplot as plt
ax = plt.plot([1,2,5,10])
pickle.dump(ax, open("plot.pickle", "wb"))

And then load it back:

import pickle
import matplotlib.pyplot as plt   
ax = pickle.load(open("plot.pickle", "rb"))
plt.show()
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59
  • I am using fig,(graph,label_texts)=plt.subplots(2,1,gridspec_kw = {'height_ratios':[4.5, 1]}) to generate my plots. and then I'm trying pickle.dump(fig,file(file_name.split('.')[0]+'_graph.pickle'‌​,'w')) which gives me: Can't pickle at 0x0CB02FB0>: it's not found as generate_graph. Which seems to be an issue with how I generate my image. Any thoughts? @Cedric – azazelspeaks Jul 25 '17 at 18:39
  • Try `pickle.dump(fig, open("plot.pickle", "wb"))` . I think you should use `open` instead of `file` – Cedric Zoppolo Jul 25 '17 at 18:44
  • I'm getting the same error. I suppose it's a pickle issue and not the open thing. – azazelspeaks Jul 25 '17 at 19:21
  • Did you try out "wb" instead of "w"? – Cedric Zoppolo Jul 25 '17 at 19:36
  • I did. The problem was pickling thing with functions in them, adding the dill library as below was the solution – azazelspeaks Jul 25 '17 at 19:43
3

@Cedric's Answer.

Additionally, if you get the pickle error for pickling functions, add the 'dill' library to your pickling script. You just need to import it at the start, it will do the rest.

azazelspeaks
  • 5,727
  • 2
  • 22
  • 39