TExcelTAD
Home › Matplotlib › Matplotlib Labels and Title

Matplotlib Labels and Title

A chart without labels forces the reader to guess what the numbers mean. Matplotlib gives every figure a title and every axis a label, and lets you style the text with fonts, sizes, colours and positions.

Axis labels and a title

plt.xlabel(), plt.ylabel() and plt.title() each take a string:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

speed = np.array([20, 40, 60, 80, 100, 120])
braking = np.array([3.5, 12, 26, 46, 72, 104])   # metres

plt.plot(speed, braking, marker="o")
plt.title("Braking distance of a car")
plt.xlabel("Speed (km/h)")
plt.ylabel("Distance (m)")
plt.show()

ax = plt.gca()
print("title :", ax.get_title())
print("xlabel:", ax.get_xlabel())
print("ylabel:", ax.get_ylabel())
title : Braking distance of a car
xlabel: Speed (km/h)
ylabel: Distance (m)

Tip: Always put the unit in the axis label, e.g. "Distance (m)". It is the single most useful thing a label can tell the reader.

Font properties

All text functions accept font keywords. You can pass them one by one or collect them in a dictionary (fontdict) and reuse it:

Keyword Example values
fontsize (or size) 12, "small", "large", "x-large"
fontweight (or weight) "normal", "bold", "light"
fontstyle (or style) "normal", "italic"
color any colour
family "serif", "sans-serif", "monospace"
python · try it yourself
import matplotlib.pyplot as plt

hours = [8, 10, 12, 14, 16, 18]
queue = [4, 11, 19, 9, 14, 6]

title_font = {"family": "serif", "color": "darkblue", "size": 18}
label_font = {"family": "serif", "color": "darkred", "size": 12}

plt.plot(hours, queue, color="darkred")
plt.title("Coffee shop queue", fontdict=title_font)
plt.xlabel("Hour of day", fontdict=label_font)
plt.ylabel("People waiting", fontdict=label_font, fontstyle="italic")
plt.show()

t = plt.gca().title
print("title size:", t.get_fontsize(), "| colour:", t.get_color())
title size: 18.0 | colour: darkblue

Positioning the title and labels

plt.title() takes loc="left", "center" or "right". A figure can even have one title in each position. Axis labels accept loc too: "left", "center" or "right" for xlabel, and "bottom", "center" or "top" for ylabel. The pad argument moves the title away from the plot (in points).

python · try it yourself
import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4], [10, 30, 20, 40])
plt.title("Quarterly revenue", loc="left", fontweight="bold")
plt.title("2024", loc="right", color="gray")
plt.xlabel("Quarter", loc="right")
plt.ylabel("k
quot;, loc="top") plt.show() ax = plt.gca() print("left title:", ax.get_title(loc="left")) print("right title:", ax.get_title(loc="right")) print("centre title is empty:", ax.get_title() == "")
left  title: Quarterly revenue
right title: 2024
centre title is empty: True

Figure titles and math text

plt.suptitle() adds a title for the whole figure, above all subplots. Any text can also contain math written in a subset of LaTeX between dollar signs. Matplotlib renders it itself, so no LaTeX installation is needed:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 5, 200)
y = np.exp(-0.6 * t) * np.cos(4 * t)

plt.plot(t, y)
plt.suptitle("Damped oscillation", fontsize=14)
plt.title(r"$y = e^{-0.6t}\,\cos(4t)
quot;) plt.xlabel(r"time $t$ (s)") plt.ylabel(r"displacement $y$ (cm)") plt.show() print(f"y starts at {y[0]:.2f} and ends at {y[-1]:.3f}")
y starts at 1.00 and ends at 0.020

Use raw strings (r"...") for math text so that backslashes like \cos are not treated as escape sequences.

Math text Renders as
r"$x^2
quot;
x squared
r"$x_i
quot;
x with subscript i
r"$\alpha, \beta, \mu
quot;
Greek letters
r"$\frac{a}{b}
quot;
a fraction
r"$\sqrt{x}
quot;
square root

Rotating tick labels

Long category names on the x axis often overlap. Rotate them with plt.xticks(rotation=...):

python · try it yourself
import matplotlib.pyplot as plt

cities = ["Amsterdam", "Barcelona", "Copenhagen", "Dubrovnik", "Edinburgh"]
visits = [42, 57, 31, 25, 38]

plt.plot(cities, visits, marker="s")
plt.xticks(rotation=30, ha="right")
plt.ylabel("Visits (thousands)")
plt.tight_layout()
plt.show()

print("Most visited:", cities[visits.index(max(visits))])
Most visited: Barcelona

ha="right" aligns the end of each rotated label with its tick, and plt.tight_layout() enlarges the margins so nothing is cut off.

Test yourself

Which function sets the label under the x axis?

  1. plt.xtitle()
  2. plt.xlabel()
  3. plt.xaxis()
  4. plt.label("x")

Why are math labels usually written as raw strings, like r"$\alpha

quot;?

  1. Raw strings render faster
  2. So that backslashes are passed to Matplotlib unchanged
  3. Matplotlib only accepts raw strings
  4. To make the text italic

What is the difference between plt.title() and plt.suptitle()?

  1. None, they are aliases
  2. suptitle titles the whole figure, title one Axes
  3. suptitle is bold
  4. title is placed below the plot