Spines & rcParams
Small details decide whether a chart looks cluttered or clean: the box around the plot, the tick marks, the background. This lesson shows how to adjust them for one Axes, and how to change Matplotlib's defaults with rcParams.
Spines: the frame around the data
The four lines framing an Axes are called spines (top, bottom, left, right). Removing the top and right spines is a popular way to make a chart lighter:
import matplotlib.pyplot as plt
years = [2019, 2020, 2021, 2022, 2023, 2024]
riders = [3.1, 1.9, 2.4, 2.9, 3.3, 3.6]
fig, ax = plt.subplots()
ax.plot(years, riders, marker="o", color="C0")
ax.spines[["top", "right"]].set_visible(False)
ax.set_ylabel("Riders (millions)")
ax.set_title("Metro ridership", loc="left")
plt.show()
print({name: s.get_visible() for name, s in ax.spines.items()}){'left': True, 'right': False, 'bottom': True, 'top': False}
Moving spines
A spine can be moved to a data position, which gives a classic "math textbook" look with the axes crossing at the origin:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2 * np.pi, 2 * np.pi, 300)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, np.sin(x), label="sin x")
ax.plot(x, 0.5 * x, label="x / 2", linestyle="--")
ax.spines["left"].set_position(("data", 0))
ax.spines["bottom"].set_position(("data", 0))
ax.spines[["top", "right"]].set_visible(False)
ax.legend(loc="upper left")
plt.show()
print("left spine position:", ax.spines["left"].get_position())left spine position: ('data', 0)
Tick appearance
ax.tick_params() styles the ticks and their labels without changing where they are:
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.bar(["Mon", "Tue", "Wed", "Thu", "Fri"], [5, 7, 3, 8, 6], color="#5c7cfa")
ax.tick_params(axis="x", length=0, labelsize=12) # no tick marks on x
ax.tick_params(axis="y", direction="in", colors="gray", width=1.5)
ax.spines[["top", "right", "left"]].set_visible(False)
ax.set_facecolor("#f8f9fa")
plt.show()
print("Axes background:", mcolors.to_hex(ax.get_facecolor()))Axes background: #f8f9fa
rcParams: changing the defaults
Every default (font size, line width, figure size, colour cycle …) lives in the dictionary-like matplotlib.rcParams (also available as plt.rcParams). There are over 300 keys:
import matplotlib.pyplot as plt
keys = ["figure.figsize", "figure.dpi", "font.size", "lines.linewidth",
"axes.grid", "axes.titlesize", "savefig.dpi"]
for k in keys:
print(f"{k:<16} = {plt.rcParams[k]}")
print("Total settings:", len(plt.rcParams))figure.figsize = [6.4, 4.8]
figure.dpi = 100.0
font.size = 10.0
lines.linewidth = 1.5
axes.grid = False
axes.titlesize = large
savefig.dpi = figure
Total settings: 316
Setting plt.rcParams["font.size"] = 14 changes all later figures in the program. As with style sheets, this is global, so in reusable code (and in this playground) prefer the temporary form, plt.rc_context():
import numpy as np
import matplotlib.pyplot as plt
clean = {
"axes.spines.top": False,
"axes.spines.right": False,
"axes.grid": True,
"grid.alpha": 0.3,
"font.size": 12,
"lines.linewidth": 2.5,
"axes.prop_cycle": plt.cycler(color=["#264653", "#2a9d8f", "#e76f51"]),
}
x = np.arange(1, 13)
with plt.rc_context(clean):
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, 20 + 2 * x, label="Plan")
ax.plot(x, 18 + 2.4 * x, label="Actual")
ax.plot(x, 22 + 1.5 * x, label="Last year")
ax.legend()
ax.set_xlabel("Month")
inside = plt.rcParams["lines.linewidth"]
plt.show()
print("line width inside:", inside, "| after:", plt.rcParams["lines.linewidth"])line width inside: 2.5 | after: 1.5
| Way to customise | Scope |
|---|---|
Keyword arguments (color=, lw=) |
One artist |
Axes methods (ax.spines, ax.tick_params) |
One Axes |
plt.rc_context({...}) / plt.style.context(...) |
Figures created inside the with block |
plt.rcParams[...] = ... / plt.style.use(...) |
Everything after, in this program |
A matplotlibrc file |
Every program on your machine |
Tip:
plt.rcdefaults()resets all rcParams to Matplotlib's built-in defaults.
Test yourself
How do you hide the top and right frame lines of an Axes?
- ax.frame(False)
- ax.spines[["top", "right"]].set_visible(False)
- ax.axis("off")
- plt.grid(False)
What is the advantage of plt.rc_context({...}) over setting plt.rcParams directly?
- It supports more keys
- The changes are undone when the with block ends
- It is the only way to change font size
- It also saves the figure
Which method changes the size and colour of tick labels without moving the ticks?
- ax.set_xticks()
- ax.tick_params()
- ax.ticklabel_format()
- ax.set_xlim()