Skip to content

How to save a figure with a transparent background in Matplotlib (with Code)

The Short Answer (TL;DR)

Pass transparent=True to fig.savefig and choose a format such as PNG that supports an alpha channel. Save the figure object explicitly so a later plotting command does not change which figure is exported.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(); ax.plot([0, 1, 2], [1, 3, 2])
fig.savefig("transparent-plot.png", transparent=True, dpi=200, bbox_inches="tight")

Detailed Implementation

This example uses synthetic data and does not need a network connection. Install the recorded package versions in a separate Python environment before running it.

python -m pip install numpy==2.5.4 pandas==3.0.6 matplotlib==3.11.2 seaborn==0.13.2
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 120)
fig, ax = plt.subplots(figsize=(5.5, 3.2), layout="constrained")
ax.plot(x, np.sin(x), color="#176b87", linewidth=2, label="sin(x)")
ax.set(xlabel="x (radians)", ylabel="sin(x)", title="Sine curve")
ax.legend(frameon=False)
fig.savefig("transparent-plot.png", transparent=True, dpi=200, bbox_inches="tight")
plt.show()

The PNG contains both fully transparent and fully opaque pixels. The curve, labels and ticks remain visible while the figure background is transparent.

Which file formats preserve transparency?

PNG and SVG support transparency. JPEG does not have an alpha channel, so it cannot preserve a transparent figure background. A file viewer may display transparent pixels against white even when the alpha channel is present.

Does transparent=True remove every filled object?

The option makes the figure and axes background patches transparent for the export. Other artists can still have fills, including annotations, bars or legend frames. The example disables the legend frame so it does not add a separate filled box.

How should transparency be checked?

Composite the export over light and dark backgrounds or inspect its alpha channel. Choose line, tick and text colors for the background on which the image will be used. Saving before plt.show is a dependable pattern when backend behavior differs.

Mathematical Context

Alpha compositing combines foreground color Cf and background color Cb as C = αCf + (1 − α)Cb. An alpha of 0 is transparent and 1 is opaque. Antialiased edges can have intermediate alpha values, allowing the curve and text to blend into the destination background.

\[ C=\alpha C_f+(1-\alpha)C_b \]

Reproducibility

Executed with Python 3.12.14; numpy 2.5.4, pandas 3.0.6, matplotlib 3.11.2, seaborn 0.13.2. Automated checks confirm the stated output properties.

Primary documentation

Related guides