This article will look at different methods to save a plot to an image file instead of displaying it usingΒ Matplotlib. Matplotlib is a plotting library in Python that is used to create figures, shapes, and graphs.Β
Note: Before diving into the methods to save the plot to an image file, instead of displaying it using Matplotlib, you must ensure that you have installed the Matplotlib module on your pc. You can install it from the Python Package Index using the following code: python -m pip install matplotlib
After installing the matplotlib
module, ensure that you have imported it at the start of your code. You also need to import the pyplot
sub-library that is used to generate the charts and the plots when using matplotlib
.
Creating a Plot
You have to create a plot first using the matplotlib module. The following program shows how to create a plot:
# Importing the matplotlib module import matplotlib.pyplot as plt # Assigning the values for the x-axis and y-axis x = [10, 15, 20, 25, 30, 35] y = [x * 5 for x in x] # Plotting the values plt.plot(x, y) # Displaying the figure plt.show()
Note: The plot()
is used to specify the arguments for the x-axis
and y-axis
to be plotted.
Recommended Read: Matplotlib Line Plot β A Helpful Illustrated Guide
We have to save the output image as an image file on the disk. So let’s look at the different ways to save the plot to an image file instead of displaying it using Matplotlib.
Method 1: Using The savefig() Method
The function name is self-explanatory. We can save the plot as an image file using the savefig()
method. The savefig()
method saves the plots in many different formats like png, jpg, svg, pdf, etc.
Syntax: pyplot.savefig(fname, dpi)
- The
fname
specifies a filename (can be full path) with a particular file extension. By default, the configuration value ofsavefig.format
is used if no extension is provided.Β - The
dpi
sets the image resolution of the file (dots per inch). Thedpi
value up to 72 works for web images, whereas the dpi value 300 is designed for an image as a pdf document. - The
bbox_inches
argument is used to alter the size of whitespaces (also known as a bounding box) around the image. By default it is set tobbox_inches = 'tight'
. Similarly, thepad_inches
argument specifies the total amount of padding around the image.
Note: Always ensure that the plt.savefig()
function is called (all the features must get specified) before the plt.show()
function. If you call the plt.savefig()
function later, then the figure won’t get saved till the plot window gets closed.
Interactive mode
The following code will save the image as “image.jpg
” in the current destination. We can also save the plot file by just clicking on the save icon that is generally displayed at the bottom of the interactive window when calling the plt.show()
function.
# Importing the matplotlib module import matplotlib.pyplot as plt # Assigning the values for x axis and y axis x = [10, 15, 20, 25, 30, 35] y = [x * 5 for x in x] # Plotting the values plt.plot(x, y) # Saving the figure plt.savefig("image.jpg") # Interactive mode plt.show()
The following example shows how we can save the plot image by altering the values the way we want.
# Importing the matplotlib module import matplotlib.pyplot as plt # Assigning the values for x axis and y axis x = [10, 15, 20, 25, 30, 35] y = [x * 5 for x in x] # Plotting the values plt.plot(x, y) # Saving figure by changing the argument values plt.savefig("image", facecolor = 'y', bbox_inches = "tight", pad_inches = 0.2, transparent = True)
Non-Interactive Mode
In the interactive mode, the figure image is always displayed even when the plt.show()
function is not called after we have saved the plot on our desktop. However, we can prevent this by forcefully closing the figure window to stop the display of the plot using the close()
method.
Example:
# Importing the matplotlib module import matplotlib.pyplot as plt # Assigning the values for x axis and y axis x = [10, 15, 20, 25, 30, 35] y = [x * 5 for x in x] # Plotting the values plt.plot(x, y) # Saving the figure plt.savefig("image.jpg") # Non-interactive mode plt.close()
To stop the image from displaying, we can also turn off the interactive mode by using the ioff()
method:
Example:
# Importing the matplotlib module import matplotlib.pyplot as plt # Assigning the values for x axis and y axis x = [10, 15, 20, 25, 30, 35] y = [x * 5 for x in x] # Plotting the values plt.plot(x, y) # Saving the figure plt.savefig("image.jpg") # Non-interactive mode plt.ioff()
Method 2: Using matplotlib.pyplot.imsave()
To save the plot to the image file instead of displaying it using Matplotlib
, we can use matplotlib.pyplot.imsave()
method. This method saves the arrays as image files.
Example:
# Importing the matplotliband NumPy module import matplotlib.pyplot as plt import numpy as np # Plotting using numpy's random img = np.random.randn(50, 100) # Saving the image file plt.imsave('image.png', img)
Conclusion
Concluding the article, we learned how to save the plot to an image file instead of displaying it using Matplotlib
. I hope this article has helped you. Please stay tuned and do subscribe for more such articles.
Matplotlib + Python is a powerful combination in data visualization and data science. This 4h time investment will make you a better coder and more effective data scientist.
