Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Formatting Text with f-strings

DS 2023 | Communicating with Data

Overview

An essential part of visualization is the use of text — words and sentences.

Text appears in many places: titles, labels, legends, and annotations.

Sometimes text comes from the data, such as the name of the busiest month or the value of a mean.

Other times, text is added to emphasize a point about a visualization or to add essential context.

Python provides a useful tool to create text that dynamically incorporates the data presented in the visualization: formatted strings call f-strings.

An f-string is created by placing an f in front of the opening quote and inserting variables in the string with braces {}.

Anything inside braces is evaluated as Python code and the resulting value is written into the string.

The process of evaluating variables within strings is called interpolation.

Putting Values into Strings

Let’s look at some simple examples.

First, we’ll import our usual libraries and some familiar datasets.

Here is the simplest case.

'There are 119 Gentoo penguins.'

Without the f, Python treats the braces as ordinary characters.

'There are {count} {species} penguins.'

The braces can hold any expression, not just a variable name.

An expression is any piece of code that produces a value.

'There are 333 penguins represented in the dataset, and 3 species.'
'The heaviest penguin weighs 6.3 kg.'

Formatting Numbers

The effective use of text requires that it be formatted properly for readers.

Take, for example, the mean of body mass.

'Mean body mass: 4207.057057057057 g'

A dozen decimal places on a plot is inelegant and not very readable.

It may also give the wrong impression about how precise your measurements are.

We can control how a value is written by adding a colon after the variable and then providing a format specification inside the braces.

For example:

'Mean body mass: 4207 g'

.0f means: write it as a fixed-point number with 0 decimal places.

Notice that the value is rounded, not cut off.

Here are some frequently use format specifications:

SpecMeans{x:spec} with x = 4207.057
.2f2 decimal places4207.06
.0fno decimal places4207
,a comma between thousands4,207.057
,.0fcommas and no decimals4,207
.1%multiply by 100, add %, 1 decimal(for x = 0.157) 15.7%
.2escientific notation4.21e+03
+.1falways show the sign+4207.1
dan integer (for int values only)(for x = 42) 42

Let’s look at a few examples.

4207.06
4,207
15.7%
4.21e+03
-4207.1  +4207.1

Width and alignment

A number before the precision sets a minimum width, padding with spaces.

<, >, and ^ align left, right, and center.

This is useful for lining up printed tables.

Adelie      3,706.2 g   (146 birds)
Chinstrap   3,733.1 g   ( 68 birds)
Gentoo      5,092.4 g   (119 birds)

Formatting Dates

Dates have their own specification language.

It uses directives that start with %.

July 1960
Jul 1960
1960-07-01
01/07/60
DirectiveMeansExample
%Yfour-digit year1960
%ytwo-digit year60
%Bfull month nameJuly
%babbreviated monthJul
%mmonth number07
%dday of the month01
%AweekdayFriday

Three Things That Trip People Up

Quotes inside the braces. To look up a column inside an f-string, use the other kind of quote.

'The first penguin is an Adelie from Torgersen.'

If the f-string uses double quotes, use single quotes inside, and the other way round.

Literal braces. To write a brace itself, double it.

'A set looks like {1, 2, 3} and has 3 items.'

Line breaks. \n inside any string starts a new line, which is handy for two-line labels.

Gentoo
n = 119

A Shortcut for Checking Values

Adding = after an expression prints the expression and its value.

It saves typing when we are checking our work.

'mean_mass=4207.1'

f-strings in Matplotlib

Can we use f-strings in plots?

Yes, anywhere Matplotlib accepts text.

That is because Matplotlib never sees the f-string itself.

Python fills in the braces first, and hands Matplotlib an ordinary, finished string.

TextWhere it goes
ax.set_title(f'...')the title of one axes
ax.set_xlabel(f'...'), ax.set_ylabel(f'...')the axis labels
fig.suptitle(f'...')a title over all the panels
ax.text(x, y, f'...')text anywhere on the plot
ax.annotate(f'...', xy=...)a callout with an arrow
ax.plot(..., label=f'...')an entry in the legend
ax.set_xticks(positions, labels=[f'...' for ...])the tick labels, one string each

Labels and titles from the data

Here we label each species’ mean body mass on a bar chart, and put a computed finding in the title.

<Figure size 640x480 with 1 Axes>

Every number on this plot came from the data.

If we filtered the data, the labels and the title would update themselves.

Legend labels

The label of each series becomes its legend entry.

Here each entry also shows how many penguins are behind it.

<Figure size 640x480 with 1 Axes>

Dates in labels

Date directives work in plot text too.

<Figure size 1000x400 with 1 Axes>

Snag 1: dollar signs

Matplotlib reads any text between two dollar signs as math, and draws it in a math font.

That is a problem for money.

<Figure size 640x480 with 1 Axes>

The dollar signs vanished, and the text between them came out in italics.

To get a literal dollar sign, put a backslash before it: \$.

Inside a Python string, a single backslash has its own meanings, so we write two, \\$, and Python passes one of them on to Matplotlib.

<Figure size 640x480 with 1 Axes>

A single dollar sign on its own is safe.

The trouble starts when a label has two.

Snag 2: braces in math

Sometimes we want math in a label, such as a Greek letter or a superscript.

Math text uses LaTeX, and LaTeX uses braces too: R2R^{2} is written $R^{2}$.

Inside an f-string, braces mean “a value goes here”, so LaTeX’s braces must be doubled, as we saw for literal braces.

Here we compute the R2R^2 of a straight-line fit and put it in the title.

<Figure size 640x480 with 1 Axes>

Read the title code piece by piece.

  • $R^{{2}}$ becomes $R^{2}$ once Python is done, which Matplotlib draws as R².

  • {r_squared:.2f} is an ordinary f-string value.

  • $\\mu$ becomes $\mu$, which Matplotlib draws as the Greek letter μ. The backslash is doubled for the same reason as with the dollar sign.

Snag 3: tick labels

Tick labels are different.

A plot has many ticks, and each needs its own label, computed from its own value.

So instead of a finished string, we give Matplotlib a format string and let it fill in each tick value.

It names that value x, and the string has no f in front.

<Figure size 1000x400 with 1 Axes>

What happens if we add the f out of habit?

Python fills in the braces immediately, using whatever x happens to mean right now.

Earlier in this notebook, we set x = 4207.057.

<Figure size 1200x400 with 2 Axes>

On the right, every tick says the same thing.

The f-string turned into the finished text '4,207k' before Matplotlib ever saw it, so there was nothing left to fill in.

If x had not been defined at all, we would have gotten a NameError instead.

The Same Specifications Elsewhere

The format specifications are a small language of their own, and other tools accept them too.

Like tick formatters, these take a plain format string, with no f.

WhereExample
A string’s .format() method'{:,.0f}'.format(4207.057)
Pandas styled tablesdf.style.format('{:.1f}')
Matplotlib bar labelsax.bar_label(ax.containers[0], fmt='{:,.0f}')
Matplotlib tick labelsax.yaxis.set_major_formatter('{x:,.0f}')

Summary

  • An f-string is a string with f before the quote. Expressions in { } are evaluated and written into it.

  • A colon after the expression starts a format specification: {x:,.2f}.

  • Dates take % directives: {date:%B %Y}.

  • Use the other kind of quote inside the braces, and double a brace to write it literally.

  • f-strings work anywhere Matplotlib takes text: titles, labels, text(), annotate(), and legend labels.

  • In plot text, write a literal dollar sign as \\$, and double the braces of any LaTeX math: $R^{{2}}$.

  • Tick formatters, bar_label(fmt=), .format(), and Pandas style.format() take a plain format string, with no f.

To write...CodeResult
a valuef'{n} birds'119 birds
1 decimalf'{x:.1f}'4207.1
thousands, no decimalsf'{x:,.0f}'4,207
a percentf'{0.157:.1%}'15.7%
a signed changef'{0.3:+.1f}'+0.3
a month and yearf'{date:%B %Y}'July 1960
a padded columnf'{s:<10}'Gentoo
a checkf'{x=:.1f}'x=4207.1
a dollar sign in a plotf'\\${v:.2f}'$12.50
math in a plotf'$R^{{2}}$ = {r2:.2f}'R² = 0.76
tick labels (no f)'{x:,.0f}k'600k