# How to Save a Figure in Matplotlib with savefig

> How to save a Matplotlib figure with savefig: file formats, dpi, bbox_inches="tight", transparent backgrounds, saving in loops and to memory, and why a saved image comes out blank.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-savefig/ | Published: 2026-11-25 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, savefig, export, png, svg, dpi, bbox_inches

To save a Matplotlib plot to a file, call `fig.savefig("chart.png")` (or `plt.savefig()` for the current figure). The file extension picks the format (`.png`, `.svg`, `.pdf`, `.jpg`), `dpi` sets the resolution, and `bbox_inches="tight"` trims extra whitespace so labels and legends aren't cut off. Call it **before** `plt.show()`, or you'll save a blank image.

## Quick Example

```python
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
online = [42, 45, 51, 58, 63, 71, 78, 74, 69, 73, 88, 104]
retail = [61, 58, 60, 62, 66, 64, 63, 65, 62, 66, 79, 96]

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(months, online, marker="o", color="#c2410c", label="Online")
ax.plot(months, retail, marker="s", color="#0e7490", label="Retail")
ax.set_title("Monthly revenue by channel ($k)")
ax.legend()

fig.savefig("revenue.png", dpi=150, bbox_inches="tight")
```

![Matplotlib line chart of monthly online and retail revenue saved to a PNG file with savefig](https://www.pythoncharts.com/matplotlib/matplotlib-savefig/images/matplotlib-savefig-quick-example.png)

That writes `revenue.png` next to your script or notebook: a line chart where online revenue climbs from 42 to 104 and passes retail in May. The code targets Matplotlib 3.10 and 3.11, but `savefig` has worked this way for years.

## The savefig Arguments You'll Actually Use

| Argument | What it does | Typical value |
|---|---|---|
| `fname` | Path or file-like object to write to | `"chart.png"` |
| `dpi` | Pixels per inch for raster formats | `150` for web, `300` for print |
| `bbox_inches` | Crop to the drawn content | `"tight"` |
| `pad_inches` | Padding kept around a tight crop | `0.1` (default) |
| `transparent` | Make the figure and axes backgrounds transparent | `True` |
| `facecolor` | Background color of the saved figure | `"white"`, `"#fef3c7"` |
| `format` | Force a format when there's no extension (e.g. a buffer) | `"png"`, `"svg"` |
| `metadata` | Key/value metadata stored in the file | `{"Title": "Revenue"}` |
| `pil_kwargs` | Extra options passed to Pillow (JPEG quality, etc.) | `{"quality": 90}` |

`fig.savefig()` and `plt.savefig()` take the same arguments. Prefer `fig.savefig()`: it saves the figure you mean, even if another figure became "current" in the meantime.

## Choose the File Format: PNG vs SVG vs PDF vs JPEG

Matplotlib reads the format from the extension, so `fig.savefig("chart.svg")` writes an SVG. To see everything your install supports:

```python
print(fig.canvas.get_supported_filetypes())
# {'eps': ..., 'jpg': ..., 'pdf': ..., 'png': ..., 'svg': ..., 'tif': ..., 'webp': ..., ...}
```

- **PNG** is the safe default for the web, slides, and docs. It's lossless and supports transparency.
- **SVG** is a vector format. It stays sharp at any zoom, is often smaller than a high-dpi PNG for simple charts, and can be edited in Figma or Illustrator. Scatter plots with tens of thousands of points make huge SVGs, though.
- **PDF** is vector too, and the usual choice for LaTeX papers and print.
- **JPEG** is lossy, so text and thin lines get fuzzy artifacts. Use it only when a system demands it, and raise the quality with `pil_kwargs={"quality": 95}`.

To save the same figure in several formats, loop over the extensions:

```python
for ext in ["png", "svg", "pdf"]:
    fig.savefig(f"revenue.{ext}", dpi=200, bbox_inches="tight")
```

`dpi` is ignored for the vector parts of SVG and PDF output, so passing it is harmless.

If the SVG needs editable text rather than text converted to paths, set `plt.rcParams["svg.fonttype"] = "none"` before saving. For PDFs that open cleanly in Illustrator, `plt.rcParams["pdf.fonttype"] = 42` embeds TrueType fonts instead of Type 3.

## Set the Resolution with dpi

`dpi` stands for dots per inch, and the pixel size of a PNG is `figsize × dpi`. An 8×4.5 inch figure saved at `dpi=150` is 1200×675 pixels before any cropping. At `dpi=300` it's 2400×1350.

```python
fig.savefig("revenue-web.png", dpi=150)    # blogs, docs, Slack
fig.savefig("revenue-print.png", dpi=300)  # print, retina screens
```

By default `dpi="figure"`, which uses the figure's own dpi (100 unless you changed it). If the chart looks right but is too small, raise `dpi`. If the fonts and lines look too small relative to the chart, change `figsize` instead. Text sizes are in points, so a smaller figure makes the text look bigger. The [figure size post](https://www.pythoncharts.com/matplotlib/figure-size-matplotlib/) covers `figsize` in more detail.

## Stop Labels and Legends Getting Cut Off with bbox_inches="tight"

The saved file keeps the figure's exact canvas size by default. Anything drawn outside it, like a legend placed outside the axes or long rotated tick labels, gets cropped. `bbox_inches="tight"` measures what's actually drawn and grows or shrinks the saved image to fit it.

```python
ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1))
fig.savefig("revenue.png", dpi=150, bbox_inches="tight", pad_inches=0.2)
```

![Two saved PNGs side by side: with the default savefig the legend placed outside the axes is cut off at the right edge; with bbox_inches tight the whole legend is included](https://www.pythoncharts.com/matplotlib/matplotlib-savefig/images/matplotlib-savefig-bbox-inches.png)

On the left, the default save clips the legend at the figure's edge. On the right, `bbox_inches="tight"` widens the image to include it. `pad_inches` controls the margin left around the content (default `0.1`).

One side effect: the output size no longer exactly equals `figsize × dpi`. If you need exact pixel dimensions, skip `bbox_inches="tight"` and fix the layout with `fig.tight_layout()` or `layout="constrained"` instead. See [Move the Matplotlib Legend Outside the Plot Box](https://www.pythoncharts.com/matplotlib/matplotlib-legend-outside/) and [adjusting subplot spacing with tight_layout](https://www.pythoncharts.com/matplotlib/matplotlib-tight-layout-subplot-spacing/).

## Transparent or Colored Backgrounds

`transparent=True` makes the figure and axes backgrounds see-through, which is what you want for a chart placed on a colored slide. `facecolor` sets a specific background color for the saved file instead.

```python
fig.savefig("units.png", transparent=True)
fig.savefig("units.png", facecolor="#fef3c7")
```

![A purple bar chart of units sold by region saved twice: with transparent=True the checkerboard shows through the background, with facecolor set the figure background is pale yellow while the axes stay white](https://www.pythoncharts.com/matplotlib/matplotlib-savefig/images/matplotlib-savefig-transparent-facecolor.png)

With `transparent=True` (left), everything except the bars, text, and axis lines is transparent, so the checkerboard shows through. With `facecolor` (right), only the area outside the axes changes color. The axes keep their own background unless you set `ax.set_facecolor()` too. There's a full walkthrough in [How to Set Plot Background Transparency in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-transparent-background-png-export/).

## Why Is My Saved Figure Blank?

Nearly always because `plt.savefig()` ran after `plt.show()`:

```python
plt.plot(online)
plt.show()
plt.savefig("blank.png")  # saves an empty figure
```

In a script, `plt.show()` blocks until you close the window, and closing it destroys the figure. The next `plt.savefig()` call creates and saves a new, empty figure. The fixes are to save before showing, or to keep a reference and call `fig.savefig()`:

```python
fig, ax = plt.subplots()
ax.plot(online)
fig.savefig("revenue.png")
plt.show()
```

A related surprise in Jupyter: the inline backend crops displayed figures as if `bbox_inches="tight"` were set, so the notebook preview can look fine while the saved file cuts off a legend. Pass `bbox_inches="tight"` to `savefig` to get the same result in the file.

## Save Many Figures in a Loop Without Running Out of Memory

Pyplot keeps every figure open until you close it. Generate a few hundred charts in a loop and you'll see `RuntimeWarning: More than 20 figures have been opened` and growing memory use. Close each figure after saving it:

```python
import numpy as np

rng = np.random.default_rng(7)
for store in ["austin", "boston", "chicago", "denver"]:
    fig, ax = plt.subplots(figsize=(6, 3.5))
    ax.plot(rng.normal(100, 12, 30).cumsum())
    ax.set_title(f"Cumulative sales: {store.title()}")
    fig.savefig(f"sales-{store}.png", dpi=120, bbox_inches="tight")
    plt.close(fig)
```

For a batch job on a server with no display, also set a non-interactive backend at the top of the script with `matplotlib.use("Agg")` (before importing `pyplot`).

## Save Several Plots to One Multi-Page PDF

`PdfPages` collects figures as pages of a single PDF:

```python
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages("store-report.pdf") as pdf:
    for store in ["austin", "boston", "chicago"]:
        fig, ax = plt.subplots(figsize=(8.5, 5))
        ax.plot(rng.normal(100, 12, 30).cumsum())
        ax.set_title(store.title())
        pdf.savefig(fig)
        plt.close(fig)
```

For reports that mix charts with text and tables, see [How to Generate PDF Data Reports with Embedded Python Charts](https://www.pythoncharts.com/python/generate-pdf-data-reports-python/).

## Save to Memory Instead of a File (BytesIO)

Web apps, email reports, and APIs often need the image as bytes rather than a file on disk. `savefig` accepts any file-like object. Pass `format`, because there's no extension to read:

```python
import base64
import io

buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
png_bytes = buf.getvalue()

# e.g. embed directly in HTML
img_tag = f'![](data:image/png;base64,{base64.b64encode(png_bytes).decode()})'
```

## Add or Strip Metadata

`metadata` writes key/value pairs into the file. The allowed keys depend on the format (PNG accepts free-form text keys; PDF uses keys like `Title`, `Author`, `Subject`):

```python
fig.savefig("revenue.png", metadata={"Title": "Monthly revenue", "Author": "Analytics team"})
```

Setting a key to `None` removes the default value. That's useful for reproducible files that don't change on every build: `metadata={"CreationDate": None}` for PDF, or `{"Date": None}` for SVG.

## Practical Tips

- Use `fig.savefig()` and save before `plt.show()`.
- `dpi=150` with `bbox_inches="tight"` is a good default for the web. Use `dpi=300` for print, or save SVG/PDF.
- If saved text looks too small, shrink `figsize` instead of raising `dpi`.
- Close figures in loops with `plt.close(fig)`.
- For Seaborn figure-level plots like `relplot` and `catplot`, call `.savefig()` on the returned grid. The [Seaborn high-resolution figures post](https://www.pythoncharts.com/seaborn/seaborn-save-high-resolution-figures/) covers those.
- For animations, `savefig` saves a single frame. Use `FuncAnimation.save()` as shown in [How to Animate Charts and Save as GIF/MP4 in Matplotlib](https://www.pythoncharts.com/matplotlib/how-to-animate-charts-and-save-as-gif-mp4-in-matplotlib/).

## Similar Topics

- [How to Set Plot Background Transparency in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-transparent-background-png-export/)
- [Saving High-Resolution Figures in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-save-high-resolution-figures/)
- [Changing the Figure and Plot Size in Matplotlib](https://www.pythoncharts.com/matplotlib/figure-size-matplotlib/)
