Thanks to theidioms.com

Matplotlib savefig method – Save plots and figures in Python

Matplotlib savefig
Data Science

Matplotlib savefig method – Save plots and figures in Python

The Matplotlib savefig method is used to save Matplotib figures in Python.


Syntax for Matplotlib savefig

The syntax for Matplotlib savefig() is as follows:

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)

Some important parameters of savefig is as follows:

  • fname: str or path-like or binary file-like

A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.

If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.

If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"] (default: 'png') and the appropriate extension is appended to fname.

The resolution in dots per inch. If ‘figure’, use the figure’s dpi value.


Usage of Matplotlib savefig

The Matplotlib savefig method can be used as shown in the example below:

import matplotlib.pyplot as plt
import numpy as np

# Sample data points
x = np.linspace(0,6,31)
y = np.exp(-0.5*x) * np.sin(x)

# Plotting
plt.plot(x, y, 'bo-')

# Saving the figure
plt.savefig('figure.png', dpi = 1200)
Matplotlib savefig

This is how you save a plot in Matplotlib using Matplotlib’s savefig method.


Matplotlib savefig method - Save plots and figures in PythonMatplotlib savefig method - Save plots and figures in Python

Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Udemy courses that we recommend you enroll in:

  1. 2022 Complete Python Bootcamp From Zero to Hero in Python - 1,000,000+ students already enrolled!
  2. Python for Data Science and Machine Learning Bootcamp - 400,000+ students already enrolled!
  3. Complete Guide to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
  4. Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!
  5. The Complete SQL Bootcamp 2021: Go from Zero to Hero - 400,000+ students already enrolled!

Leave your thought here

Your email address will not be published. Required fields are marked *