Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 57 ยท Line Plots and Basic Styling

Titles, Labels, Text and Math

Add titles, axis labels and free text to Matplotlib charts, control font size, weight and family, rotate labels, and write formulas with mathtext.

A chart without words is a riddle. The title says what you are looking at, the axis labels say what is measured and in which unit, and extra text points out what matters. Matplotlib gives you methods for each job, plus a built-in math typesetter so you can show formulas without installing LaTeX.

This lesson uses the ax.set_* methods of the object-oriented API from pyplot vs the object-oriented API. Annotations with arrows get their own lesson later: Annotations and Arrows.

Words on a chart

Title ax.set_title says what it is.
Axis labels Say what and in which unit.
Free text ax.text puts a note anywhere.
Math Dollar signs switch on mathtext.

Every method takes the same font keywords.

1 / 2

Titles and axis labels

ax.set_title, ax.set_xlabel and ax.set_ylabel take a string and styling keywords. The same keywords work for all text in Matplotlib.

Keyword Meaning
fontsize Size in points, or "small", "large", "x-large"
fontweight "normal", "bold", or a number from 100 to 900
fontstyle "normal" or "italic"
color Any color notation from colors
loc Title and x label: "left", "center", "right". Y label: "bottom", "center", "top"
pad Gap between title and axes, in points
labelpad Gap between label and the tick labels

A good axis label includes the unit in parentheses: "Distance (km)" is better than "Distance". A good title states the finding or the subject, not the chart type: "Sales grew every quarter" beats "Line chart of sales".

Python Titles, labels and the font keywords

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that set_title can be called more than once with different loc values, which gives you a main title on the left and a small note on the right. The call fig.suptitle(...) puts a title above a whole figure that contains several axes. You will use it in multiple subplots.

Placing text with ax.text

ax.text(x, y, "words") writes text at a position given in data coordinates: the same numbers as on your axes. Useful options are ha and va (horizontal and vertical alignment relative to the point), rotation, bbox for a background box, and transform=ax.transAxes to switch to axes fractions, where (0, 0) is the lower-left corner and (1, 1) the upper-right. Axes fractions are ideal for notes that must stay in a corner no matter how the data changes.

Python Text in data and axes coordinates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If you resize the axes or change the limits, the "peak" label follows the data point, while the yellow note stays where it is. Choose the coordinate system that matches what the text is attached to.

Math with mathtext

Any string that contains text between a pair of dollar signs is typeset as math. Matplotlib ships its own engine called mathtext, which understands a large subset of LaTeX syntax with no external install. Use a raw string (r"...") so Python does not treat backslashes as escapes.

You write You get
r"$\alpha, \beta, \pi$" Greek letters
r"$x^2$" and r"$x_i$" superscript and subscript
r"$\frac{a}{b}$" a fraction
r"$\sqrt{x}$" square root
r"$\sum_{i=1}^{n} x_i$" a sum with limits
r"$\mu \pm \sigma$" symbols such as plus-minus

Plain text and math mix freely: r"Area = $\pi r^2$". Use braces to group more than one character in a superscript or subscript, for example $x^{10}$; without braces only the next character is raised.

Python Formulas in titles, labels and text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By default mathtext uses a font that matches the surrounding text reasonably well. You can change the family with rcParams["mathtext.fontset"] (values such as "dejavusans", "cm" and "stix"); see Styles, rcParams and Themes for how to set defaults. A full LaTeX installation can be switched on with usetex=True, but that needs LaTeX on the machine, so it is not available on this site.

Font families and rotated labels

The fontfamily keyword picks a family: "serif", "sans-serif", "monospace", "cursive" or "fantasy", or the name of a font that is installed. Matplotlib falls back to a default font if the one you name is missing, and it prints a warning in that case. For consistent output on many machines stick to the generic family names.

Long tick labels collide. Rotate them with ax.tick_params(axis="x", labelrotation=45), or set rotation=45, ha="right" when you call ax.set_xticklabels so the end of each label sits under its tick. For very long category names, a horizontal bar chart is usually the better choice; see bar charts.

Python Font families and rotated tick labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With ha="right" each rotated label ends right under its bar. Without it, rotated labels center on the tick and appear shifted to the left.

Choosing and inspecting fonts

Matplotlib does not use the fonts of your operating system blindly. It keeps a font manager (matplotlib.font_manager) with a list of every font file it found, and each time you name a font it searches that list. That explains most font surprises: a name that works on your laptop fails on a server that does not have the font installed.

There are four ways to say which font you want, from broadest to narrowest:

Where Example Effect
Global default plt.rcParams["font.family"] = "serif" every text in every later figure
Candidate list plt.rcParams["font.sans-serif"] = ["Arial", "DejaVu Sans"] first installed name in the list wins
One text element ax.set_title("Hi", fontname="DejaVu Serif") only that title
A reusable object FontProperties(family="serif", style="italic", weight="bold", size=16) pass as fontproperties= wherever you need it

font.family can be a generic family ("serif", "sans-serif", "monospace", "cursive", "fantasy") or the name of one real font. Generic families are looked up in the matching list, font.serif, font.sans-serif and so on. Putting your first-choice font at the front of such a list and a font that always exists ("DejaVu Sans" ships with Matplotlib) at the end is the safe way to get "my font, or a good fallback". If nothing in the list is found, Matplotlib logs a "findfont" message and uses DejaVu Sans instead of failing.

Python Which fonts exist, and what happens with a missing one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The list printed on this page is the list of the browser runner (DejaVu, STIX and Computer Modern fonts). On your own machine it will include your system fonts, so run the first lines locally to see which names you can use. The title uses a FontProperties object: it bundles family, style, weight and size, so one object can style many labels. The x label uses fontname= (a short way to name a single font), and the y label uses family=, which is the same keyword as fontfamily.

To use a font file that is not installed, call font_manager.fontManager.addfont("path/to/Font.ttf") once, then use its name like any other. Put the font file next to your project so everybody who clones it gets the same chart.

Moving axis labels

By default an axis label sits centered next to the tick labels. Three tools change that:

  • labelpad sets the distance in points between the tick labels and the axis label: ax.set_xlabel("time", labelpad=20). Use it when long tick labels, or a rotated tick label, crowd the label.
  • loc moves the label along the axis. For x labels the values are "left", "center" and "right"; for y labels "bottom", "center" and "top". Placing the x label at the right end, under the arrow tip of the axis, reads like a textbook diagram.
  • ax.xaxis.set_label_coords(x, y) (and ax.yaxis.set_label_coords) puts the label at exact Axes coordinates, where (0, 0) is the lower left corner of the Axes and (1, 1) the upper right. This is how you line up the y labels of several stacked charts, so they sit on one vertical line whatever the tick labels' width.
Python labelpad, loc and set_label_coords

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that once you call set_label_coords, that label stays exactly where you put it: it no longer moves with labelpad or with the width of the tick labels. The tick label size has its own knob, ax.tick_params(labelsize=...); see Ticks, Locators and Formatters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call writes text pinned to the top-left corner of the axes, no matter the data limits?

    transform=ax.transAxes switches the coordinates to axes fractions, where (0, 1) is the upper-left corner.
  2. 2. Why should formulas usually be written as raw strings such as r"$\alpha$"?

    In a normal string some backslash sequences (like \n or \t) are escapes. A raw string keeps the backslash for mathtext.
  3. 3. How do you write x to the power of 10 in mathtext?

    Without braces only the next character is raised, so x^10 gives x to the power 1 followed by a 0.
  4. 4. What does ha="right" do on rotated tick labels?

    Horizontal alignment relative to the anchor point. For rotated labels, right alignment makes the label end under the tick.

Summary

  • set_title, set_xlabel and set_ylabel label a chart; loc, pad and labelpad adjust the position, and fig.suptitle titles a whole figure.
  • Font keywords (fontsize, fontweight, fontstyle, fontfamily, color) work on every piece of text.
  • ax.text uses data coordinates by default; add transform=ax.transAxes for fractions of the axes, and bbox=dict(...) for a background box.
  • Text between dollar signs is typeset by mathtext: Greek letters, fractions, roots, sums, super- and subscripts. Use raw strings and braces.
  • Rotate crowded tick labels with rotation and ha="right", or switch to horizontal bars.

Next, control how much of the data is visible in Limits, Scales and Aspect.