What is the matplotlib.pyplot.savefig() function in Python?
Overview
matplotlib is one of the multiple libraries that Python provides us with.
The main purpose of matplotlib is to provide us with data visualization. This library is based on numpy, and the purpose of designing this library is to work with the border SciPy stack.
Matplotlib has a sub-library known as pyplot, which makes it a visual open-source like Matlab.
savefig() is a function provided by the matplotlib.pyplot library, and is used to save plotted images on the local machine.
Syntax
savefig(fname, dpi=None, facecolor='w', edgecolor='w',orientation='portrait', papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)
Parameters
-
fname: This refers to a file name or file location. -
dpi: This is the number of dots per inch. -
facecolor: This controls the background color of the saved image. By default, the color will be white. -
edgecolor: This is used to add the border to the figure. By default, this is white. -
orientation: This can be a landscape or portrait orientation. -
papertype: This tells us which type of paper we want to use, like a letter, legal, a0 to a10, or something else. -
format: This is the file format.
transparent: This makes the picture’s background transparent.
-
bbox_inches: This tells us how the image will be fit. -
pad_inches: This indicates the padding around the image.
Code
# Importing modulesimport matplotlib.pyplot as plt# Initialising datax=[1,2,3,4,5,6,7,8,9,10]y=[5,2,4,7,1,3,2,8,1,0]# Ploting dataplt.plot(x,y)# Saving plotted imageplt.savefig("output/plotted_data.png")
Explanation
- Line 2: We import the
matplotlib.pyplotlibrary. - Lines 5–6: We initialize the data.
- Line 9: We plot the data initialized above.
- Line 12: We save the image and display it as output.
Free Resources