5

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)

7
  • Do you want to save the graph, or the underlying data? Commented Jul 25, 2017 at 18:00
  • @DavidZ The underlying data, the array or whatever that holds the graph data. Commented Jul 25, 2017 at 18:02
  • Maybe you can use pickle to save your object and then load it again later? docs.python.org/2/library/pickle.html Commented Jul 25, 2017 at 18:08
  • matplotlib.pyplot.plot and others return the underlying data you can pickle and save for later use. Commented Jul 25, 2017 at 18:11
  • 2
    You can check this question stackoverflow.com/questions/7290370/… Commented Jul 25, 2017 at 18:14

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

5 Comments

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: <class 'pickle.PicklingError'> Can't pickle <function <lambda> at 0x0CB02FB0>: it's not found as generate_graph.<lambda> Which seems to be an issue with how I generate my image. Any thoughts? @Cedric
Try pickle.dump(fig, open("plot.pickle", "wb")) . I think you should use open instead of file
I'm getting the same error. I suppose it's a pickle issue and not the open thing.
Did you try out "wb" instead of "w"?
I did. The problem was pickling thing with functions in them, adding the dill library as below was the solution
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.