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')
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.
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.
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.
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))
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With