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.
import matplotlib.pyplot as plt
# Creating data year = [ '2010' , '2002' , '2004' , '2006' , '2008' ]
production = [ 25 , 15 , 35 , 30 , 10 ]
# Plotting barchart plt.bar(year, production) # Saving the figure. plt.savefig( "output.jpg" )
# Saving figure by changing parameter values 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().
import matplotlib.pyplot as plt
import numpy as np
# Generate a 2D NumPy array (image data) image_data = np.random.rand( 100 , 100 ) # Generate random image data of size 100x100
# Display the image using Matplotlib plt.imshow(image_data, cmap = 'gray' )
plt.title( 'Sample Image' )
plt.axis( 'off' ) # Turn off axis numbers and ticks
# Save the image using matplotlib.pyplot.imsave() plt.imsave( 'sample_image.png' , image_data, cmap = 'gray' )
# Show the image plt.show() |
Output:
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.
import matplotlib.pyplot as plt
from PIL import Image
fig, ax = plt.subplots()
ax.plot([ 1 , 2 , 3 ], [ 1 , 2 , 3 ])
# Convert Matplotlib figure to PIL Image fig.canvas.draw() buf = fig.canvas.tostring_rgb()
width, height = fig.canvas.get_width_height()
pil_image = Image.frombytes( "RGB" , (width, height), buf)
# Save PIL Image as PNG pil_image.save( 'pil_image_save.png' )
|
Output: