Matplotlib savefig function is for saving matplotlib plot into an image file like “.png” or “.pdf”. Let’s see other parameters of savefig().
Matplotlib savefig Implementation-
Let’s see this complete implementation with example into steps.
Step 1: Importing packages-
In this section, We will only import the packages for the complete example of savefig() example.
import matplotlib.pyplot as plt import numpy as np
As we have imported matplotlib for plotting graph. We have imported the numpy for data creation for plotting the graph.
Step 2: Datapoint creation –
See it’s an optional step. Because in the real scenario we already have data points. But here for a demonstration of savefig() function, we will create some data points.
x =np.arange(1,5) y1 = x+10 y2 = x*3 y3 = x/2 plt.plot(x,y1,color="red") plt.plot(x,y2,color="pink") plt.plot(x,y3,color="black")
The above code is for drawing three different lines in a single line chart in matplotlib plot.
Step 3: save plot using savefig() matplotlib –
In this step, we will see how can see save the plot into an image in matplotlib.
As we can see in the above section that savefig() created a “.png” at a local disk. Here we can change this filetype and other parameters. In the next section, We will see those parameters.
Complete syntax for savefig() –
savefig(fname, dpi=None, facecolor=None edgecolor=None, orientation=None, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=None, frameon=None, metadata=None)
Parameters with savefig() –
There are so many parameters which we can tweak in savefig(). Most of them are self-explanatory in nature. We will not discuss them in this section. In this section, We will see the selected parameters which are mostly in use.
1. fname- Here we can define the output location of the image with its format type.
2. dpi – It can control the picture quality. Basically, it is pixel ooer inch.
3. Orientation – It is optional in [Landscape or Portrait]
4. format – It is for deciding the format of the file [“.pdf”, “.png” or etc]
Well, I hope this article must give you an idea of saving plots into an image using Matplotlib. Please put your views on the comment box.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.