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 Python Matplotlib savefig method - Save plots and figures in Python

Leave your thought here

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