[python] 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')

This question is related to python matplotlib

The answer is


Here's the piece of code that saves plot to the selected directory. If the directory does not exist, it is created.

import os
import matplotlib.pyplot as plt

script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, 'Results/')
sample_file_name = "sample"

if not os.path.isdir(results_dir):
    os.makedirs(results_dir)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig(results_dir + sample_file_name)

In addition to the answers already given, if you want to create a new directory, you could use this function:

def mkdir_p(mypath):
    '''Creates a directory. equivalent to using mkdir -p on the command line'''

    from errno import EEXIST
    from os import makedirs,path

    try:
        makedirs(mypath)
    except OSError as exc: # Python >2.5
        if exc.errno == EEXIST and path.isdir(mypath):
            pass
        else: raise

and then:

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

# Create new directory
output_dir = "some/new/directory"
mkdir_p(output_dir)

fig.savefig('{}/graph.png'.format(output_dir))

You just need to put the file path (directory) before the name of the image. Example:

fig.savefig('/home/user/Documents/graph.png')

Other example:

fig.savefig('/home/user/Downloads/MyImage.png')

The simplest way to do this is as follows:


save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)

The image is going to be saved in the save_results_to directory with name image.png


Here is a simple example for saving to a directory(external usb drive) using Python version 2.7.10 with Sublime Text 2 editor:

import numpy as np 
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256, endpoint = True)
C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color = "blue", linewidth = 1.0, linestyle = "-")
plt.plot(X, S, color = "red", linewidth = 1.0, linestyle = "-")

plt.savefig("/Volumes/seagate/temp_swap/sin_cos_2.png", dpi = 72)

You should be able to specify the whole path to the destination of your choice. E.g.:

plt.savefig('E:\New Folder\Name of the graph.jpg')

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.


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))        

You can use the following code

name ='mypic'
plt.savefig('path_to_file/{}'.format(name))

If you want to save in same folder where your code lies,ignore the path_to_file and just format with name. If you have folder name 'Images' in the just one level outside of your python script, you can use,

name ='mypic'
plt.savefig('Images/{}'.format(name))

The default file type in saving is '.png' file format. If you want to save in loop, then you can use the unique name for each file such as counter of the for loop. If i is the counter,

plt.savefig('Images/{}'.format(i))

Hope this helps.