To change the background color in Matplotlib, set the facecolor: ax.set_facecolor("lightyellow") colours the plot area inside the axes, and fig.set_facecolor("lightblue") (or plt.figure(facecolor=...)) colours the figure around it. To change the default background color for every plot, set plt.rcParams["axes.facecolor"] and plt.rcParams["figure.facecolor"]. This guide covers all of these, plus dark mode with dark_background, transparent PNGs, subplots, the legend and text boxes.
Tested with Python 3.12.5 and Matplotlib 3.11.2. Charts are real Matplotlib windows; console output is from the Windows Command Prompt. See the official docs for Axes.set_facecolor and customizing Matplotlib with style sheets and rcParams.
Figure background vs axes background
A Matplotlib chart has two backgrounds. The figure is the whole window or image; the axes is the rectangle where the data is drawn. Both are set with a facecolor:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
fig.set_facecolor("#e8eef6") # the figure: the area around the plot
ax.set_facecolor("#fffbe6") # the axes: the area inside the plot
ax.plot([2019, 2020, 2021, 2022, 2023, 2024], [41, 38, 45, 52, 58, 63], marker="o", color="tab:blue")
ax.set_title("Monthly active users (thousands)")
plt.show()
| What to colour | Code |
|---|---|
| Axes (plot area) | ax.set_facecolor("color") or plt.gca().set_facecolor("color") |
| Figure (outer area) | fig.set_facecolor("color"), fig.patch.set_facecolor("color") or plt.figure(facecolor="color") |
| Every new plot | plt.rcParams["axes.facecolor"] and plt.rcParams["figure.facecolor"] |
| Saved file only | fig.savefig("out.png", facecolor="color") or transparent=True |
Colours can be names ("black"), hex strings ("#1e1e2e"), RGB(A) tuples with values from 0 to 1, or grey levels as strings ("0.9").
Change the background color of one subplot
Each axes has its own facecolor, so you can colour subplots individually. Pass facecolor to plt.subplots() to colour the figure at the same time:
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.6), facecolor="lightgray") # figure colour at creation
for ax in (ax1, ax2):
ax.plot([1, 2, 3, 4], [3, 1, 4, 2])
ax1.set_title("Axes facecolor: default (white)")
ax2.set_facecolor("black") # only this subplot
ax2.tick_params(colors="dimgray")
ax2.set_title("ax2.set_facecolor('black')")
plt.tight_layout()
plt.show()
Change the default background color for all plots
Set the rcParams at the top of your script (or in a matplotlibrc file) and every figure created afterwards uses them. First, what the defaults are:
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
print("figure.facecolor =", plt.rcParams["figure.facecolor"])
print("axes.facecolor =", plt.rcParams["axes.facecolor"])
print("savefig.facecolor =", plt.rcParams["savefig.facecolor"])
plt.rcParams["figure.facecolor"] = "#f4f1ea" # every new figure
plt.rcParams["axes.facecolor"] = "#fbfaf6" # every new axes
fig, ax = plt.subplots()
print("\nnew figure:", to_hex(fig.get_facecolor()))
print("new axes: ", to_hex(ax.get_facecolor()))
Output:
figure.facecolor = white
axes.facecolor = white
savefig.facecolor = auto
new figure: #f4f1ea
new axes: #fbfaf6
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.facecolor"] = "#f4f1ea"
plt.rcParams["axes.facecolor"] = "#fbfaf6"
plt.rcParams["axes.edgecolor"] = "#8a8170"
x = np.linspace(0, 10, 200)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6))
axes[0].plot(x, np.sin(x))
axes[1].plot(x, np.exp(-x / 3), color="tab:orange")
fig.suptitle("Background set once with rcParams")
plt.tight_layout()
plt.show()
facecolor argument.savefig.facecolor is "auto" by default, which means saved files use the figure’s own background colour.
Dark background (dark mode) with a style sheet
Style sheets change the background together with text, tick and grid colours. dark_background is the built-in dark mode:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("dark_background") # black figure and axes, white text and ticks
x = np.linspace(0, 4 * np.pi, 300)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
ax.set_title("plt.style.use('dark_background')")
ax.legend()
plt.show()
plt.style.use("dark_background").You can list the styles that ship with Matplotlib and see which background each one uses. plt.style.context() applies a style only inside a with block:
import matplotlib.pyplot as plt
names = [s for s in plt.style.available if "dark" in s or s in ("ggplot", "bmh", "fivethirtyeight")]
print(len(plt.style.available), "styles available; some that change the background:")
for name in names:
with plt.style.context(name):
print(f" {name:<22} figure={plt.rcParams['figure.facecolor']:<8} axes={plt.rcParams['axes.facecolor']}")
Output:
28 styles available; some that change the background:
bmh figure=white axes=#eeeeee
dark_background figure=black axes=black
fivethirtyeight figure=#f0f0f0 axes=#f0f0f0
ggplot figure=white axes=#E5E5E5
seaborn-v0_8-dark figure=white axes=#EAEAF2
seaborn-v0_8-dark-palette figure=white axes=white
seaborn-v0_8-darkgrid figure=white axes=#EAEAF2
Transparent background when saving
savefig(..., transparent=True) removes the figure and axes backgrounds from the saved PNG, which is useful for slides and web pages with their own background. savefig(facecolor=...) sets a background for the file only. To prove the difference, the script reads the top-left pixel of each file:
import matplotlib.pyplot as plt
from PIL import Image
fig, ax = plt.subplots(figsize=(4, 3))
ax.bar(["A", "B", "C"], [4, 7, 5], color="tab:green")
fig.savefig("normal.png")
fig.savefig("transparent.png", transparent=True) # no background at all
fig.savefig("custom_bg.png", facecolor="#0b1f33") # background only in the file
for name in ("normal.png", "transparent.png", "custom_bg.png"):
corner = Image.open(name).convert("RGBA").getpixel((2, 2)) # top-left pixel (R, G, B, alpha)
print(f"{name:<16} corner pixel = {corner}")
Output:
normal.png corner pixel = (255, 255, 255, 255)
transparent.png corner pixel = (255, 255, 255, 0)
custom_bg.png corner pixel = (11, 31, 51, 255)
JPEG files cannot be transparent; save as PNG or SVG.
Legend and text background color
The legend box and text boxes have their own backgrounds, which matter most on dark plots:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
ax.set_facecolor("#1e1e2e")
ax.plot([1, 2, 3, 4, 5], [2, 4, 3, 6, 7], color="#89b4fa", label="Visits")
ax.plot([1, 2, 3, 4, 5], [1, 2, 2, 3, 5], color="#f9e2af", label="Sign-ups")
ax.legend(facecolor="white", edgecolor="black", framealpha=1) # legend background
ax.text(3, 6.3, "Campaign launch", color="black",
bbox=dict(facecolor="#a6e3a1", edgecolor="none", boxstyle="round,pad=0.4")) # text background
plt.show()