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.

Annotations

DS 2023 | Communicating with Data

Overview

Effective visualizations use language and visual symbols to direct the reader’s attention to what is salient in a visualization.

There are two major areas of concern:

Labeling

  • All parts of a plot or group of plots should be labeled.

  • Parts include axes, ticks, geometries (dots, bars, etc.), legends, the figure, etc.

  • Sometimes it is effective to remove text.

  • In all cases, the goal is to make the plot completely legible and intelligble.

Adding context

  • Annotation includes providing information needed to properly interpret the visualization.

  • Information includes data sources, units of measurement, scales, etc.

Emphasizing

  • Annotation also includes the use of visual devices and text labels.

  • These things often are often overlaid on the plot to highlight its part.

  • Examples inclide a region of a scatter plot or a high point in a trend.

Annotative devices

Among the specific devices used to annotate an image are:

  • text: a label placed anywhere on the plot.

  • arrows: used to direct attention to a specific element.

  • callouts: text with an arrow pointing to a feature.

  • reference lines: a vertical or horizontal line to indicate a threshold, an average, a target, a date, etc.

  • regions: a shaded band for a period, a range, or a gap between two series, etc..

  • labels on marks: text used to show the actual value printed on each bar, etc.

  • shapes: a box or ellipse drawn around a cluster, etc.

  • emphasis: one series in color while the others are gray, etc.

  • figure-level marks: a title over several panels, panel letters, lines that connect one panel to another.

Some specific use cases

  • Marking an event: a recession, a policy change, a pandemic year on a time series.

  • Labeling an extreme: the busiest month, the largest outlier, the record high.

  • Showing a threshold: break-even, a passing grade, a legal limit, the mean.

  • Comparing to a range: one country against the band formed by all the others.

  • Reading exact values: counts printed on bars when readers need the numbers.

  • Guiding a multi-panel figure: panel letters, a shared title, a zoom from an overview to a detail.

Set Up

We will use two wide tables throughout, shaped as in earlier notebooks.

Each has years in the index and one column per series.

Understanding how to position annotations

To actually place an annotation on a figure, we need to know how Matplotlib handles positions.

There are actually three coordinate systems in play.

SystemRuns fromUse it when the annotation belongs to...
Data (the default)the x and y axis valuesa data point or value
Axes fraction(0,0)(0, 0) at the bottom left of the axes to (1,1)(1, 1) at the top righta position in the plot box, such as a corner
Figure fraction(0,0)(0, 0) to (1,1)(1, 1) across the whole figurethe figure as a whole, across panels

Let’s put one label in each system.

<Figure size 1000x500 with 1 Axes>

The blue label is tied to the data.

  • If the axis limits change, it moves with the line.

The orange label is tied to the axes box, through transform=ax.transAxes.

  • By default, the x and y you give ax.text() are in data coordinates, i.e. the position of (x,y) in the cartesian plane.

  • With transform=ax.transAxes, the numbers are read as fractions of the axes.

  • So, (0, 0) is the bottom-left corner of the plot box and (1, 1) is the top-right/

The green label is tied to the figure, and sits below the axes entirely.

Text

The function ax.text(x, y, s) writes the string s at the point (x, y).

It is the simplest annotation, and every other text annotation is built on it.

Its most useful parameters control alignment and appearance.

ParameterDoes
hahorizontal alignment of the text relative to the point: 'left', 'center', 'right'
vavertical alignment: 'bottom', 'center', 'top', 'baseline'
fontsize, fontweight, colorappearance
rotationangle in degrees
bboxa dictionary describing a box behind the text
transformthe coordinate system, such as ax.transAxes

Alignment confuses almost everyone at first.

ha='left' does not move the text to the left.

It puts the left edge of the text at the point.

Let’s see all three settings at once, with a dot marking the point.

<Figure size 800x300 with 1 Axes>

Direct labeling

A common use of text() is to label lines directly, at their ends, instead of with a legend.

The reader no longer has to match colors between the legend and the plot.

Here is life expectancy, with each country labeled at its last year.

Loading...
<Figure size 1000x600 with 1 Axes>

The .plot() method returns a list of the lines it drew.

We can ask for the color of each line with get_color() and give the label the same color.

Direct labels work best when the line ends are well separated.

When they are not, you have to nudge the labels by hand or fall back on a legend.

Text in a box

The bbox parameter of ax.text() draws a box behind the text.

It is useful for notes that sit on top of data, where the box keeps the text readable.

<Figure size 1000x500 with 1 Axes>

Callouts with annotate()

The ax.annotate() function is text() with an arrow.

It takes two positions:

  • xy, a tuple of the the point being annotated, i.e. where the arrow ends,

  • xytext, a tuple of the place where the text goes, i.e. where the arrow starts.

The arrow is drawn only if we pass a dictionary of properties to arrowprops.

Here we point to the busiest month in the flights dataset.

date 1949-01-01 112 1949-02-01 118 1949-03-01 132 1949-04-01 129 1949-05-01 121 Name: passengers, dtype: int64
1960-07-01 00:00:00 622
<Figure size 1000x500 with 1 Axes>

Notice that we did not type the date or the number into the label.

We computed them with idxmax() and max(), so the annotation stays correct if the data change.

Using offsets instead of positions

Choosing xytext in data coordinates can be awkward, because we must think in dates and passengers to place a label.

Often it is easier to say how far the text should be from the point, in screen units.

textcoords='offset points' does this.

A point is 1/72 of an inch, the unit of font sizes.

<Figure size 1000x500 with 1 Axes>

Each label sits 25 points directly above its point, whatever the axis scales are.

The July peak more than quadrupled in twelve years.

Arrow styles

arrowprops accepts many options.

The two we use most are arrowstyle and connectionstyle, which bends the arrow.

<Figure size 1000x400 with 1 Axes>

'arc3,rad=0.3' curves each arrow; rad=0 is straight.

A gentle curve can route an arrow around data that a straight arrow would cross.

Reference lines

A reference line marks a value that is not in the data but helps us read it: an average, a target, a date.

MethodDraws
ax.axhline(y)a horizontal line across the whole axes
ax.axvline(x)a vertical line across the whole axes
ax.hlines(y, xmin, xmax)horizontal segments with set ends, one or many
ax.vlines(x, ymin, ymax)vertical segments with set ends, one or many
ax.axline(xy1, xy2) or ax.axline(xy1, slope=m)an infinite line through a point at any angle

Lines are usually paired with text().

Here are penguin body masses, with the overall mean as a reference.

<Figure size 1000x500 with 1 Axes>

The transform argument in the text() uses the argument ax.get_xaxis_transform().

This lets the user specify a location along the line.

  • In the case of a vertical lines, a value of 0 means at the bottom and 1 means at the top.

  • So, with a value of .98, each label sits at its line’s x value, near the top of the plot, whatever the heights of the bars.

Notice that the mean is to the right of the median.

That is what we expect from a right-skewed distribution.

A diagonal reference

Use axline() to draw lines at any angle.

In a scatter plot of two measurements in the same units, the line y = x is often the most useful reference.

Here is Japan’s life expectancy against the USA’s, one point per year.

<Figure size 600x600 with 1 Axes>

Notice that every point is above the line.

So in every year with data, Japan’s life expectancy was higher than the USA’s.

The distance from the line is the size of the gap, and it grows as we move up and to the right.

One point jumps far to the left of its neighbors: 2020, when the USA lost almost two years and Japan did not.

Without the line, the eye has nothing to measure against.

Regions

Some annotations mark an area rather than a value.

Spans

  • ax.axvspan(xmin, xmax) shades a vertical band across the whole height of the axes.

  • ax.axhspan(ymin, ymax) shades a horizontal one.

Here is USA life expectancy, with the first pandemic year shaded.

<Figure size 1000x500 with 1 Axes>

The span runs from 2019.5 to 2020.5 so that it is centered on the 2020 data point.

Bands between curves with fill_between()

ax.fill_between(x, y1, y2) shades the region between two curves.

If we leave out y2, it fills down to 0.

We used it in Area Charts to draw areas.

Here we use it to annotate: to show a range against which one series can be compared.

Let’s shade the band from the lowest to the highest life expectancy among the five other countries, and draw the USA on top.

<Figure size 1000x500 with 1 Axes>

Here we can see something that no single line shows.

Until the mid-1980s, the USA sat inside the range of the others.

Then it fell below it and never came back.

What year does the USA leave the band?

You can find it with (life.USA < others.min(axis=1)).

Shading a gap with where

fill_between() has a where parameter that shades only where a condition is true.

With it, we can color the gap between two series differently depending on which is higher.

The USA is below the other five on average in every year, so that comparison would be all one color.

Let’s compare the USA with Germany instead.

<Figure size 1000x500 with 1 Axes>

Until 1984, Americans could expect to live slightly longer than Germans.

From 1985 on, the order reversed, and the gap has widened ever since.

The spike in 1990 and the break in 1991 come from the German data around reunification, not from a real change in lifespans.

An odd feature like this is something to check, and perhaps annotate, before we draw attention to it.

interpolate=True finds where the two lines cross, so the colors meet exactly at the crossing instead of at the nearest year.

This is the difference chart from Area Charts, which goes back to William Playfair’s 1786 chart of England’s trade with Denmark and Norway.

Here it is doing the work of an annotation: the color tells us what to read in the gap.

Labels on marks

When readers need exact values, we can print them on the marks.

For bar charts, ax.bar_label() does this in one call.

It takes the container of bars that a bar plot returns, which Pandas stores in ax.containers.

<Figure size 700x400 with 1 Axes>

bar_label() also takes a fmt string, or a list of labels for full control.

Here are the same bars labeled with percentages.

<Figure size 700x400 with 1 Axes>

For other plots, we label points with text() or annotate() in a loop.

Here is a scatter plot of car weight against fuel economy, with the five most efficient cars named.

offset points keeps each label a little to the right of its point.

<Figure size 1000x600 with 1 Axes>

Labels that overlap each other are the usual problem with this approach.

Label only the points that matter to the story, and nudge the rest by hand.

Shapes with patches

Sometimes we want to point at a group of points, not a single one.

The matplotlib.patches module provides shapes such as Rectangle, Circle, Ellipse, and Polygon.

We create a shape, then add it to the axes with ax.add_patch().

Here we circle the Gentoo penguins, which form their own cluster in the bill measurements.

<Figure size 800x600 with 1 Axes>

The ellipse is centered on the Gentoo means and spans two standard deviations each way.

So it is computed from the data, not drawn by eye.

Notice that we did not color the points by species.

The shape alone points the reader to one group, and lets the others stay in the background.

Emphasis

A powerful technique is to draw a contrast.

If everything is colored, nothing stands out.

If one series is colored and the rest are gray, the reader knows where to look.

<Figure size 1000x600 with 1 Axes>

Notice that the title is used to train the users’ attention to what the plot shows.

Annotating a set of plots

When a figure has several panels, some annotations belong to the figure rather than to any one axes.

MethodAnnotates
fig.suptitle()a title over all the panels
fig.supxlabel(), fig.supylabel()shared axis labels
fig.text()text anywhere on the figure, in figure fractions
fig.legend()one legend for all the panels
ax.text(..., transform=ax.transAxes)panel letters, the same position in every panel
ConnectionPatcha line from a point in one axes to a point in another

Let’s combine them.

The figure below shows the whole flights series, then zooms in on one year.

Lines connect the zoomed region in the overview to the detail panel.

<Figure size 1200x800 with 3 Axes>

Read the figure as a reader would.

The title states the finding.

Panel A shows the trend, and the shaded span tells us that Panel B is a closer look at 1958.

The connecting lines make that link explicit.

The panel letters let a caption or a paragraph refer to each part, as in “see Panel C”.

The source line credits the data.

Every one of these marks is an annotation.

Notice how ConnectionPatch uses a different coordinate system at each end: a blended transform in Panel A and an axes fraction in Panel B.

It also needs plain numbers, not dates, so we convert each date with xaxis.convert_units().

Other Ways to Annotate

A few more tools are worth knowing.

  • Titles, labels, and legends. set_title(), set_xlabel(), set_ylabel(), and legend() are annotations we use on every plot. ax.set_title(loc='left') places a title flush left, a common style in reports.

  • Math text. Any label can include LaTeX math between dollar signs, as in ax.set_xlabel(r'$\mu$ (g)').

  • Custom ticks. ax.set_xticks(positions, labels=...) replaces tick labels with words, such as event names on a time axis.

  • Grid lines. ax.grid(axis='y') adds light reference lines at every tick, for reading values.

  • Secondary axes. ax.secondary_xaxis() and ax.secondary_yaxis() show a second scale for the same data, such as Celsius beside Fahrenheit.

  • Insets. ax.inset_axes([x, y, w, h]) places a small axes inside another, and ax.indicate_inset_zoom() draws the box and connecting lines for us.

  • Error bars and intervals. ax.errorbar() and Seaborn’s errorbar parameter mark uncertainty around a value.

  • Images and logos. fig.figimage() and ax.imshow() can place an image, such as a logo or an icon.

  • Interactive tooltips. In Plotly, which is in our environment, hover_data shows annotations when the reader points at a mark.

When Annotations Mislead

Annotations are claims.

They tell readers what the data mean, and readers tend to believe them.

  • Implied causes. A shaded span labeled with an event invites the reader to see the event as the cause of whatever happens inside it. Shade an event only when the connection is part of the argument, and say so in the text.

  • Arbitrary references. A reference line looks like a standard. A mean, a legal limit, and a number we chose ourselves all look the same once drawn. Label every line with what it is.

  • Cherry-picked labels. Labeling the extreme points draws attention to them. If they are unusual, say so; if the labels were chosen to support a story, the story is weaker than it looks.

  • Annotations that hide data. A box or a label placed on top of the data covers the very observations it describes. Move it, make its background transparent, or point to the data from the outside.

  • Stale annotations. Hand-typed values and positions stop being true when the data change. Compute them.

  • Clutter. Every annotation competes with every other. If everything is labeled, the reader is back to reading a table.

Summary

  • An annotation is any mark that guides the reader’s interpretation without encoding an observation.

  • Annotations are placed in a coordinate system: data, axes fraction, figure fraction, or a blend.

  • ax.text() writes text; ha and va align it relative to its point; bbox puts it in a box.

  • ax.annotate() adds an arrow from xytext to xy; textcoords='offset points' places text relative to the point.

  • Reference lines (axhline, axvline, hlines, vlines, axline) mark values; spans (axvspan, axhspan) mark intervals.

  • fill_between() shades a range or a gap, and where shades it conditionally.

  • bar_label() prints values on bars; patches circle or box a group; gray-and-color emphasis points the eye.

  • Figure-level methods annotate a set of plots: suptitle, supxlabel, fig.text, panel letters, and ConnectionPatch.

  • Every annotation is a claim. Compute it from the data, label it clearly, and use as few as the story needs.

TaskCode
Text at a data pointax.text(x, y, 'label', ha='left', va='center')
Text in a cornerax.text(0.02, 0.98, 'note', transform=ax.transAxes, va='top')
Text in a boxax.text(..., bbox=dict(boxstyle='round', facecolor='white'))
Callout with arrowax.annotate('label', xy=(x, y), xytext=(x2, y2), arrowprops=dict(arrowstyle='->'))
Offset labelax.annotate('label', xy=(x, y), xytext=(0, 10), textcoords='offset points')
Horizontal or vertical lineax.axhline(y), ax.axvline(x)
Line at any angleax.axline((x, y), slope=1)
Label at a line’s x, near the topax.text(x, 0.95, 'label', transform=ax.get_xaxis_transform())
Shaded intervalax.axvspan(x1, x2, alpha=0.2)
Band between curvesax.fill_between(x, low, high)
Conditional gapax.fill_between(x, y1, y2, where=y1 > y2, interpolate=True)
Values on barsax.bar_label(ax.containers[0])
Shape around a groupax.add_patch(Ellipse(center, w, h, fill=False))
Title over panelsfig.suptitle('...')
Line between panelsfig.add_artist(ConnectionPatch(xyA, xyB, coordsA, coordsB))