How to Save a Plot to a File Using Matplotlib?
Matplotlib is a widely used Python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. In this article, we will see how to save a Matplotlib plot as an image file.
Save a plot in Matplotlib
Below are the ways by which we can save a plot to a file using Matplotlib in Python:
- Using savefig()
- Using matplotlib.pyplot.imsave()
- Using Pillow Library
The savefig MethodÂ
The figure produced after data plotting is saved using the savefig() method, as the name implies. Using this technique, the generated figure can be saved to our local computers.
In this example, we are creating our own data list, and using Matplotlib we are plotting a bar graph and saving it to the same directory. To save generated graphs in a file on a storage disk, savefig() method is used.
Python3
import matplotlib.pyplot as plt
year = [ '2010' , '2002' , '2004' , '2006' , '2008' ]
production = [ 25 , 15 , 35 , 30 , 10 ]
plt.bar(year, production)
plt.savefig( "output.jpg" )
plt.savefig( "output1" , facecolor = 'y' , bbox_inches = "tight" ,
pad_inches = 0.3 , transparent = True )
|
Output:
Â
Â
Matplotlib Save Plot as Image Using matplotlib.pyplot.imsave()
Using the matplotlib.pyplot.imsave() method, we may save the plot to an image file rather than using Matplotlib to display it. The arrays are saved using this manner as picture files.
Syntax: matplotlib.pyplot.imsave(fname, arr, **kwargs
Parameter:
- fname: A path or a file-like object to store the image.
- arr: The image data.Â
Return: Save an array as an image file.
In this method, we are trying to read an image using imread() function, and save the same image with a different name using imsave().
Python3
import matplotlib.pyplot as plt
import numpy as np
image_data = np.random.rand( 100 , 100 )
plt.imshow(image_data, cmap = 'gray' )
plt.title( 'Sample Image' )
plt.axis( 'off' )
plt.imsave( 'sample_image.png' , image_data, cmap = 'gray' )
plt.show()
|
Output:
sample_image.png
Matplotlib Save Plot as Image Using PIL Module
In this example, a Matplotlib figure is created with a simple line plot. The figure is then converted to a PIL Image object and saved as a PNG file using the Pillow library.
Python3
import matplotlib.pyplot as plt
from PIL import Image
fig, ax = plt.subplots()
ax.plot([ 1 , 2 , 3 ], [ 1 , 2 , 3 ])
fig.canvas.draw()
buf = fig.canvas.tostring_rgb()
width, height = fig.canvas.get_width_height()
pil_image = Image.frombytes( "RGB" , (width, height), buf)
pil_image.save( 'pil_image_save.png' )
|
Output:
pil_image_save.png
Last Updated :
09 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...