Skip to content
Related Articles

Related Articles

Improve Article

How to Save a Plot to a File Using Matplotlib?

  • Last Updated : 03 Jan, 2021

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. To save generated graphs in a file on storage disk, savefig() method is used.

savefig() : Save the current figure.

Syntax: pyplot.savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)

Parameters:

  • fname : path or name of output file with extension. If extension is not provided plot is saved as png file. Supported file formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.
  • dpi : dots per inch resolution of figure
  • facecolor : facecolor of figure
  • edgecolor :  edgecolor of figure
  • orientation  : landscape or portrait
  • format : The file format, e.g. ‘png’, ‘pdf’, ‘svg’, etc.
  • transparent : If  it is True, the patches of axes will all be transparent

Steps:



  1. Plot a graph
  2. Use pyplot.savefig() method to save generated plot in a file

Example:

Python3




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:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :