Matplotlib rcParams: Set Global Plot Defaults

Change Matplotlib's default figure size, fonts, colors, spines, and grid with rcParams, apply settings temporarily, reset them, and save them to a style file.

plt.rcParams is a dictionary of Matplotlib's default settings. Change it with plt.rcParams.update({...}) near the top of a script and every figure created afterwards uses the new figure size, fonts, colors, and grid.

Quick Example

import matplotlib.pyplot as plt
import numpy as np
from cycler import cycler

plt.rcParams.update({
    "figure.figsize": (8, 4.2),
    "figure.constrained_layout.use": True,
    "font.size": 12,
    "axes.titlesize": 15,
    "axes.titleweight": "bold",
    "axes.titlelocation": "left",
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.grid": True,
    "axes.grid.axis": "y",
    "grid.alpha": 0.35,
    "axes.prop_cycle": cycler(color=["#d97706", "#2563eb", "#059669"]),
    "lines.linewidth": 2.5,
    "legend.frameon": False,
})

rng = np.random.default_rng(52)
month = np.arange(1, 13)
season = 1 - np.cos(2 * np.pi * month / 12)
output = {
    name: size * (0.5 + season) + rng.normal(0, size * 0.08, 12)
    for name, size in {"Roof A": 190, "Roof B": 140, "Carport": 85}.items()
}

def chart():
    fig, ax = plt.subplots()
    for name, kwh in output.items():
        ax.plot(month, kwh, label=name)
    ax.set_title("Solar output by array")
    ax.set_xlabel("Month")
    ax.set_ylabel("kWh")
    ax.set_xticks(month)
    ax.legend(ncols=3)
    plt.show()

chart()

Solar output line chart styled through rcParams with a bold left-aligned title, custom colors, horizontal gridlines, and no top or right spines

None of that styling is in the plotting code. The examples target Matplotlib 3.11; cycler is installed along with Matplotlib.

Find the Setting You Need

There are more than 300 keys. Filter them by name, and read a current value like any dictionary entry:

print([key for key in plt.rcParams if key.startswith("axes.title")])
print(plt.rcParams["figure.dpi"])

The first line prints ['axes.titlecolor', 'axes.titlelocation', 'axes.titlepad', 'axes.titlesize', 'axes.titleweight', 'axes.titley']. A misspelled key raises a KeyError that suggests valid names, and a value of the wrong type raises a ValueError.

Common rcParams

Setting Key Built-in default
Figure size in inches figure.figsize [6.4, 4.8]
Screen resolution figure.dpi 100.0
Saved resolution savefig.dpi "figure"
Crop saved files savefig.bbox None (use "tight")
Base font size font.size 10.0
Font family font.family ["sans-serif"]
Axes title size axes.titlesize "large"
Tick label size xtick.labelsize, ytick.labelsize "medium"
Line width lines.linewidth 1.5
Gridlines axes.grid False
Top and right borders axes.spines.top, axes.spines.right True
Series colors axes.prop_cycle The tab10 colors
Heatmap and image colormap image.cmap "viridis"

Relative sizes such as "large" scale with font.size, so raising that one value enlarges titles and tick labels together.

Set a Group of Settings with plt.rc()

plt.rc() takes a group name and sets several keys in it:

plt.rc("lines", linewidth=2.5, markersize=7)  # lines.linewidth, lines.markersize
plt.rc("axes", titlesize=15, titleweight="bold")

Change Settings Temporarily with rc_context

plt.rc_context() applies settings inside a with block and restores the previous values afterwards.

dark = {
    "figure.facecolor": "#0f172a",
    "axes.facecolor": "#0f172a",
    "text.color": "#e2e8f0",
    "axes.labelcolor": "#e2e8f0",
    "axes.edgecolor": "#475569",
    "xtick.color": "#cbd5e1",
    "ytick.color": "#cbd5e1",
    "grid.color": "#94a3b8",
    "axes.prop_cycle": cycler(color=["#fbbf24", "#60a5fa", "#34d399"]),
}

with plt.rc_context(dark):
    chart()

The same solar chart on a dark navy background with light text and brighter line colors

Call plt.show() or fig.savefig() inside the block, since some settings are read when the figure is drawn or saved. For a ready-made dark theme, use plt.style.use("dark_background").

Color Cycle, Line Styles, and Markers

axes.prop_cycle sets what each new line gets. Add two cyclers to change color and line style together, which keeps series distinct in black and white.

styles = (cycler(color=["#111827", "#6b7280", "#9ca3af"])
          + cycler(linestyle=["-", "--", ":"]))

with plt.rc_context({"axes.prop_cycle": styles}):
    chart()

The solar chart in black and gray with solid, dashed, and dotted lines

Save Your Defaults to a Style File

To reuse settings across projects, put them in a .mplstyle file with one key: value per line. Write hex colors without #, because # starts a comment.

from pathlib import Path

Path("report.mplstyle").write_text("""\
figure.figsize: 8, 4.2
figure.constrained_layout.use: True
font.size: 11
font.family: serif
axes.spines.top: False
axes.spines.right: False
axes.prop_cycle: cycler(color=['7c3aed', 'db2777', '0891b2'])
legend.frameon: False
""")

plt.rcdefaults()
with plt.style.context("report.mplstyle"):
    chart()

The solar chart in a serif font with purple, pink, and teal lines, loaded from a style file

plt.style.use("report.mplstyle") applies it for the rest of the session. A file named matplotlibrc uses the same format and loads automatically. Matplotlib looks in the current working directory first, then the MATPLOTLIBRC environment variable, then your user config folder. matplotlib.matplotlib_fname() prints the file in use.

Reset rcParams to the Defaults

import matplotlib as mpl

mpl.rcdefaults()          # Matplotlib's built-in defaults
mpl.rc_file_defaults()    # the values loaded from your matplotlibrc at startup

Which Setting Wins?

From lowest to highest priority:

  1. Built-in defaults.
  2. Your matplotlibrc file.
  3. plt.style.use() and plt.rcParams changes, whichever ran last.
  4. Arguments in the call, such as ax.plot(x, y, lw=4).

A style sheet only overwrites the keys it defines, so call plt.style.use() first and your own rcParams changes second. The style sheets guide compares the built-in styles.

Similar Topics