Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Matplotlib savefig() Function

Matplotlib savefig() Function


Matplotlib Reference Documentation Matplotlib Reference Documentation

savefig() Used to save the current Figure to an image file, supporting multiple formats such as PNG, PDF, SVG, EPS, etc.

It is the core method for exporting Matplotlib charts to shareable, document-embeddable files.

Function definition

pyplot interface

matplotlib.pyplot.savefig(fname, *, dpi='figure', format=None,
    metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto',
    edgecolor='auto', backend=None, **kwargs)

Figure method

Figure.savefig(fname, *, dpi='figure', format=None, metadata=None,
    bbox_inches=None, pad_inches=0.1, facecolor='auto',
    edgecolor='auto', backend=None, **kwargs)

Parameter Description

Parameters Type Description
fname str or Path or file-like Output filename or file object. The extension automatically determines the format, such as 'plot.png', 'plot.pdf', 'plot.svg'
dpi float or 'figure' Output resolution (dots per inch). 'figure' uses the Figure's own dpi. Common values: 72 (screen), 150 (general), 300 (print)
format str Output format, such as 'png', 'pdf', 'svg', 'eps', 'jpg'. If not specified, inferred from the filename
bbox_inches str or Bbox Cropping bounds: 'tight' (compact cropping, removing extra whitespace), None (use the Figure's original size)
pad_inches float Padding (in inches) when bbox_inches='tight', default 0.1
facecolor color or 'auto' Background color of the output image, 'auto' uses the Figure's facecolor
edgecolor color or 'auto' Border color of the output image
transparent bool If True, the background is set to transparent (png/svg only)
metadata dict Metadata written to the file (supported by some formats)

Must be plt.show() before every backward pass savefig(), because show() clears the Figure. Or use fig.savefig() to specify the Figure object.

Supported file formats

Format Extension Feature
PNG .png Bitmap, supports transparency, most commonly used
PDF .pdf Vector graphic, suitable for publications, can be embedded in LaTeX
SVG .svg Vector graphic, editable in browsers/editors
EPS .eps Vector graphic, traditional publishing format
JPEG .jpg / .jpeg Bitmap, lossy compression, small file but no transparency support
TIFF .tiff / .tif Bitmap, lossless, suitable for archiving

Usage examples

Example 1: Basic saving

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

10

,

100

)

fig

,

ax

=

plt.

subplots

(

figsize

=

(

6

,

4

)

)

ax.

plot

(

x

,

np.

sin

(

x

)

,

label

=

'sin(x)'

)

ax.

set_title

(

'Save Figure Demo'

)

ax.

legend

(

)

Save as PNG

fig.

savefig

(

'runoob_plot.png'

)

print

(

"runoob: saved as runoob_plot.png"

)

Save as PDF (vector)

fig.

savefig

(

'runoob_plot.pdf'

)

print

(

"runoob: saved as runoob_plot.pdf"

)

plt.

show

(

)

Example 2: High-resolution output + tight cropping

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

fig

,

ax

=

plt.

subplots

(

figsize

=

(

8

,

4

)

)

x

=

np.

linspace

(

0

,

2

*np.

pi

,

100

)

ax.

plot

(

x

,

np.

sin

(

x

)

,

label

=

'sin(x)'

)

ax.

plot

(

x

,

np.

cos

(

x

)

,

label

=

'cos(x)'

)

ax.

set_title

(

'High Resolution Output'

)

ax.

set_xlabel

(

'Angle (rad)'

)

ax.

legend

(

loc

=

'outside'

)

 

Place the legend outside

dpi=300: high-definition quality (suitable for printing)

bbox_inches='tight': automatic cropping to ensure the legend is not cut off

fig.

savefig

(

'runoob_hires.png'

,

dpi

=

300

,

bbox_inches

=

'tight'

)

print

(

"runoob: high-res image saved"

)

plt.

show

(

)

Example 3: Transparent background + different formats

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

fig

,

ax

=

plt.

subplots

(

figsize

=

(

6

,

4

)

)

Set a dark background to demonstrate the transparency effect

fig.

patch

.

set_facecolor

(

'#2c3e50'

)

ax.

set_facecolor

(

'#34495e'

)

ax.

plot

(

np.

random

.

randn

(

100

)

.

cumsum

(

)

,

        color

=

'#1abc9c'

,

linewidth

=

2

)

ax.

set_title

(

'Transparent Background'

,

             color

=

'white'

,

fontsize

=

14

)

ax.

tick_params

(

colors

=

'white'

)

Transparent background PNG

fig.

savefig

(

'runoob_transparent.png'

,

            transparent

=

True

,

         

Transparent background

            dpi

=

150

,

bbox_inches

=

'tight'

)

SVG can also be transparent

fig.

savefig

(

'runoob_transparent.svg'

,

            transparent

=

True

,

            bbox_inches

=

'tight'

)

print

(

"runoob: transparent images saved"

)

plt.

show

(

)

Example 4: Batch saving multiple subplots

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Create a large figure containing multiple chart types

data

=

np.

random

.

randn

(

4

,

100

)

for

i

in

range

(

4

)

:

    fig

,

ax

=

plt.

subplots

(

figsize

=

(

6

,

4

)

)

    ax.

plot

(

data

[

i

]

.

cumsum

(

)

,

color

=

f

'C{i}'

,

linewidth

=

2

)

    ax.

set_title

(

f

'Series {i+1}'

)

    ax.

set_xlabel

(

'Step'

)

    ax.

set_ylabel

(

'Cumulative Sum'

)

    ax.

grid

(

True

,

alpha

=

0.3

)

   

Batch save, filenames include the index

    fig.

savefig

(

f

'runoob_series_{i+1}.png'

,

                dpi

=

200

,

bbox_inches

=

'tight'

)

    plt.

close

(

fig

)

 

Close to avoid display

print

(

"runoob: 4 figures saved (series_1 to series_4)"

)


Common questions

The saved image is blank?

Check whether savefig() is called after show(). show() may clear the Figure.

Solution: call savefig() before show(), or use fig.savefig() to specify the Figure object.

Text/labels in the image are cut off?

Use bbox_inches='tight' Automatic cropping to ensure all elements are within the image.

If the problem persists, you can increase the pad_inches parameter value.

Matplotlib Reference Documentation Matplotlib Reference Documentation