Style Sheets
A style sheet is a named bundle of settings (colours, fonts, grid, background, line widths) that changes the look of every chart at once. Matplotlib ships with about 30 of them, and you can write your own.
Listing the available styles
import matplotlib.pyplot as plt
styles = sorted(plt.style.available)
print(len(styles), "styles available")
print([s for s in styles if not s.startswith(("seaborn", "_"))])28 styles available
['Solarize_Light2', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'tableau-colorblind10']
The list above hides the internal _... styles and the many seaborn-v0_8-... entries, which reproduce the look of older seaborn versions.
Using a style
In a script you normally activate a style once at the top, and it applies to every figure that follows:
import matplotlib.pyplot as plt
plt.style.use("ggplot") # all later figures use ggplot's lookplt.style.use() changes global settings for the rest of the program. In this course's playground, the Python interpreter stays alive between runs, so a global style would "leak" into other examples. We therefore use the context manager form, which applies a style only inside a with block and restores the old settings afterwards:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
with plt.style.context("ggplot"):
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin")
ax.plot(x, np.cos(x), label="cos")
ax.set_title("The ggplot style")
ax.legend()
inside = plt.rcParams["axes.facecolor"]
plt.show()
print("Axes background inside the block:", inside)
print("Axes background after the block :", plt.rcParams["axes.facecolor"])Axes background inside the block: #E5E5E5
Axes background after the block : white
The figure keeps the style it was created with; only figures created after the block get the defaults again.
Comparing styles
Drawing the same chart in a loop of styles is the easiest way to choose one:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
data = rng.normal(0, 1, (3, 20)).cumsum(axis=1)
chosen = ["default", "ggplot", "bmh", "fivethirtyeight", "dark_background", "grayscale"]
for name in chosen:
with plt.style.context(name):
fig, ax = plt.subplots(figsize=(4, 2.4))
for row in data:
ax.plot(row)
ax.set_title(name)
fig.tight_layout()
plt.show()
print("Drew", len(chosen), "figures")Drew 6 figures
Combining styles
Styles can be stacked: pass a list and later entries override earlier ones. Matplotlib includes small "modifier" styles for exactly this purpose, such as "seaborn-v0_8-talk" (bigger text for slides) or "tableau-colorblind10" (a colour cycle that works for colour-blind readers):
import matplotlib.pyplot as plt
values = {"North": [3, 5, 4, 6], "South": [2, 4, 5, 5], "East": [4, 3, 3, 4], "West": [1, 2, 4, 6]}
with plt.style.context(["bmh", "tableau-colorblind10"]):
fig, ax = plt.subplots()
for name, v in values.items():
ax.plot(["Q1", "Q2", "Q3", "Q4"], v, marker="o", label=name)
ax.legend()
ax.set_title("bmh + colour-blind friendly cycle")
cycle = plt.rcParams["axes.prop_cycle"].by_key()["color"]
plt.show()
print("First colours of the cycle:", cycle[:4])First colours of the cycle: ['#006BA4', '#FF800E', '#ABABAB', '#595959']
Your own style
A style sheet is just a text file of key: value lines, with the same keys as rcParams (see Spines & rcParams). Save it as mystyle.mplstyle and load it with plt.style.use("./mystyle.mplstyle"):
# mystyle.mplstyle
axes.grid: True
grid.alpha: 0.3
axes.spines.top: False
axes.spines.right: False
font.size: 11
lines.linewidth: 2
axes.prop_cycle: cycler("color", ["264653", "2a9d8f", "e9c46a", "f4a261", "e76f51"])Without a file, you can apply the same settings from a dictionary using plt.rc_context({...}), covered in the next lesson.
| Function | Effect |
|---|---|
plt.style.available |
List of style names |
plt.style.use(name) |
Apply globally for the rest of the program |
plt.style.context(name) |
Apply only inside a with block |
plt.style.use("default") |
Back to Matplotlib's defaults |
Test yourself
Why does this course use with plt.style.context(...) instead of plt.style.use(...)?
- context is faster
- The style applies only inside the block and is undone afterwards
- use() doesn't exist in Matplotlib 3.8
- context() supports more styles
What happens with plt.style.use(["ggplot", "tableau-colorblind10"])?
- Only ggplot is used
- An error: one style at a time
- Both are applied; the second overrides overlapping settings
- Two figures are created
How do you return to Matplotlib's normal look after plt.style.use("ggplot")?
- plt.style.use("default")
- plt.style.reset()
- plt.close()
- It is not possible