Matplotlib is a visualization module in Python that helps to create various plots. We can use the Matplotlib module to show the complexities of the dataset in different graphs. Sometimes, we need to save these plots as a image, and today in this post, we will learn how to save plot as image in Matplotlib module. First, we will create a simple plot and then save the plot as an image.
Save the Plot as an Image in Matplotlib
The two most common methods that are used to save the plat as an image in Matplotlib module are savefig() and imsave(). Let us now understand these functions and their parameter values before using them.
The parameters of savefig() function are as follows:
- fname: the file name or the path of the file
- dpi: Represents the resolution of the image
- metadata: It is the value pair to store in the image
- bbox_inches: Save the given portion of the image
- pad_inches: Represents the amount of padding
- face color: change the color of the image
- edgecolor: change the edge color
- paper type: type of the paper
- format: specifies the extension of the image
- transparent: Either to make the background transparent or not.
The parameters of imsave() function are given below:
- fname: Path to save the file
- cmap: This is used to specify the color of the image
- dpi: resolution of the image
- vmin and vmax: set the color scale for the image
- format: Extension of the image
- arr: The data of the image
Plotting Graph in Matplotlib
Before going to save the plot, first, we have to plot it. We will create a random dataset and then will use the module to plot a simple line chart. Let us create the dataset.
import random # creating the dataset y= random.sample(range(10, 30), 5) x = [i for i in range(5)]
Now, let us plot the graph in the Matplotlib module:
# importing the module import matplotlib.pyplot as plt # plotting plt.plot(x, y) plt.show()
Now let us save this plot as an image
Save plot in image using imsave() and savefig() methods
Let us first use the imsave() method and see how it actually works:
import numpy as np fig= plt.figure() # make an agg figure fig.canvas.draw() # grab the pixel buffer X = np.array(fig.canvas.renderer.buffer_rgba()) # saving an image using the imsave function plt.imsave('Sample.png',X)
This will save the plot as an image with .png extension.
Now, let us see how we can use the savefig() and save the plot in the specified directory:
This one line of code will save the graph as an image with the extension of .png.
Matplotlib is a popular module among data scientists. It is used to plot various graphs. Sometimes, we need to save these graphs as images and in this tutorial, we learn about it. We can use the imsave() and savefig() methods respectivily to get the plot as a image.
You May Also Like:
- How to Delete Cell in Jupyter Notebook?
- Create Streamlit Button and Style Streamlit Buttons in Python
- 3D plots in Python Using Plotly and Matplotlib