How Do I Use Matplotlib Savefig ? Steps with Example

Matplotlib Savefig example

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

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.

matplotlib savefig example
matplotlib savefig example

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]


Conclusion –

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.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages, where he and his team share knowledge and help others learn more about data science.
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner