Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save matplotlib file to a directory

Here is the simple code which generates and saves a plot image in the same directory as of the code. Now, is there a way through which I can save it in directory of choice?

import matplotlib import matplotlib.pyplot as plt  fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(100))  fig.savefig('graph.png') 
like image 239
khan Avatar asked Jul 07 '12 08:07

khan


People also ask

How do I save a matplotlib file?

Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

How do I save multiple figures in Python?

Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once. Create a new PdfPages object, pp. Get the number of open figures. Iterate the opened figures and save them into a file.

How do I save a matplotlib file as a JPEG?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.


2 Answers

If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:

    fig.savefig('Sub Directory/graph.png') 

If you wish to use an absolute path, import the os module:

    import os     my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.     ...     fig.savefig(my_path + '/Sub Directory/graph.png') 

If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:

    import os     my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.     my_file = 'graph.png'     ...     fig.savefig(os.path.join(my_path, my_file))         
like image 135
Eric Avatar answered Oct 03 '22 14:10

Eric


According to the docs savefig accepts a file path, so all you need is to specify a full (or relative) path instead of a file name.

like image 41
KL-7 Avatar answered Oct 03 '22 12:10

KL-7