TExcelTAD
Home › Matplotlib › Annotations & Text

Annotations & Text

A chart becomes a story when it points out what matters: the record high, the moment a policy changed, the outlier. Matplotlib can place free text anywhere and draw annotations with arrows pointing at data.

ax.text()

ax.text(x, y, "text") writes text at a position in data coordinates:

python · try it yourself
import matplotlib.pyplot as plt

year = [2018, 2019, 2020, 2021, 2022, 2023]
users = [1.2, 1.9, 3.4, 3.1, 4.0, 4.6]

fig, ax = plt.subplots()
ax.plot(year, users, marker="o")
for x, y in zip(year, users):
    ax.text(x, y + 0.15, f"{y}M", ha="center", fontsize=9)
ax.set_ylim(0, 5.2)
ax.set_title("Active users")
plt.show()

print("Text objects:", len(ax.texts))
Text objects: 6

ha (horizontal alignment: left, center, right) and va (vertical: top, center, bottom, baseline) say which part of the text sits on the given point.

Coordinate systems

Data coordinates move with the data. For text that should stay put (a corner note, a watermark), use Axes coordinates, where (0, 0) is the bottom-left and (1, 1) the top-right corner of the Axes:

transform= Coordinates
ax.transData (default) data values
ax.transAxes 0–1 across the Axes
fig.transFigure 0–1 across the whole figure
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(12)
values = rng.normal(100, 15, 400)

fig, ax = plt.subplots()
ax.hist(values, bins=25, color="C0", alpha=0.8)
summary = f"n = {values.size}\nmean = {values.mean():.1f}\nstd = {values.std():.1f}"
ax.text(0.97, 0.95, summary, transform=ax.transAxes, ha="right", va="top",
        family="monospace", bbox=dict(boxstyle="round", facecolor="white", alpha=0.8))
plt.show()

print(summary)
n = 400
mean = 100.4
std = 14.9

The bbox argument draws a box behind the text. boxstyle can be "square", "round", "round4", "sawtooth" and more.

ax.annotate() with arrows

annotate() connects a label to a point. xy is the point being annotated and xytext is where the text goes; arrowprops styles the arrow:

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

hours = np.arange(0, 24)
load = 300 + 120 * np.sin((hours - 9) / 24 * 2 * np.pi) + 60 * np.sin((hours - 6) / 12 * 2 * np.pi)
peak = load.argmax()

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(hours, load, marker=".")
ax.annotate(f"Peak: {load[peak]:.0f} MW at {hours[peak]}:00",
            xy=(hours[peak], load[peak]),
            xytext=(hours[peak] + 2, load[peak] + 100),
            arrowprops=dict(arrowstyle="->", color="black"))
ax.set(xlabel="Hour", ylabel="Grid load (MW)", ylim=(0, 550))
plt.show()

print("Peak hour:", hours[peak], "| load:", round(float(load[peak])))
Peak hour: 11 | load: 390

Useful arrowstyle values: "->", "-|>", "<->", "fancy", "wedge". Add connectionstyle="arc3,rad=0.3" to curve the arrow.

Offsets in points

Instead of choosing xytext in data units, give it as an offset in points with textcoords="offset points". The label then keeps the same distance from the point at any zoom level, which is perfect for labelling scatter points:

python · try it yourself
import matplotlib.pyplot as plt

cities = {"Lisbon": (8.6, 3.0), "Madrid": (6.2, 3.3), "Paris": (11.2, 2.1),
          "Berlin": (10.4, 3.7), "Rome": (9.9, 4.4)}

fig, ax = plt.subplots()
for name, (rent, growth) in cities.items():
    ax.scatter(rent, growth, color="C1")
    ax.annotate(name, (rent, growth), xytext=(5, 5), textcoords="offset points")
ax.set(xlabel="Average rent (€ per m², made up)", ylabel="Growth (%)")
ax.margins(0.15)
plt.show()

print("Labelled", len(ax.texts), "cities")
Labelled 5 cities

Highlighting regions

axvspan and axhspan shade a vertical or horizontal band; together with text they mark periods and ranges:

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

week = np.arange(1, 27)
signups = np.array([30, 32, 31, 35, 34, 36, 38, 37, 60, 72, 75, 70, 52, 45,
                    44, 46, 47, 45, 48, 50, 49, 52, 51, 53, 55, 54])

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(week, signups, color="C0")
ax.axvspan(9, 12, color="C1", alpha=0.2)
ax.text(10.5, 78, "Campaign", ha="center", color="C1", fontweight="bold")
ax.axhline(signups[:8].mean(), color="gray", linestyle=":")
ax.set(xlabel="Week", ylabel="Sign-ups", ylim=(0, 85))
plt.show()

print("Campaign average:", signups[8:12].mean(), "| before:", signups[:8].mean())
Campaign average: 69.25 | before: 34.125

Test yourself

In ax.annotate("Max", xy=(3, 9), xytext=(1, 7), arrowprops=dict(arrowstyle="->")), where does the arrow point?

  1. At (1, 7)
  2. At (3, 9)
  3. At the centre of the Axes
  4. Nowhere, there is no arrow

Which transform keeps text in the top-right corner of an Axes regardless of the data?

  1. ax.transData with x=1, y=1
  2. ax.transAxes with x=0.95, y=0.95
  3. fig.dpi_scale_trans
  4. No transform is needed

What does textcoords="offset points" mean for xytext=(5, 5)?

  1. Text at data position (5, 5)
  2. Text 5 points right and 5 points up from xy
  3. Font size 5
  4. 5 % of the figure size