Enriching Data Visualizations with Annotations in Plotly using Python

“A picture is worth a thousand words.” Indeed it is, and an annotated picture is worth its contribution to data literacy.

Reshama Shaikh
Nerd For Tech
6 min readAug 15, 2021

--

With the advances in programming and computing, data scientists can now do state-of-the-art visualizations without requiring in-depth knowledge of D3 or Javascript. We can accomplish this using the python library plotly!

For these examples, I am using Python version 3.9 and plotly version 5.1.0.

A video version of annotations in plotly is available on YouTube.

Enriching Data Visualizations with Annotations in Plotly (10-minute presentation)

STEP 1: Read in sample data for visualization

Look at data frame, by sampling a few rows: df.sample(5)

STEP 2: Create a basic, 2-group, line plot

STEP 3: Extend the x-axis range a bit

Let’s extend the x-axis on the left and right a little bit, so it is cleaner and easier to read and the graph doesn’t go to the edges.

This parameter gives options for the x-axis range: range_x=[..., ...]

STEP 4: Add an author and data source footnote

This allows us to add a footnote annotation: fig.add_annotation(...).

Tip: you may want to adjust the above values for x and y as well as for xshift and yshift, depending on the size of your graph.

Tip: the br in the footnote text represents a line break.

STEP 5: Add an annotation with a box & opacity

Tip: there are many options for how text in annotations can be presented. There are options for font size, type and color. There are options for adding boxes around text with various formatting options. Arrows can be shown or hidden, using the showarrow=True option.

Tip: the location of the annotation “145 is the maximum value” can be placed using the coordinates, in this case, x='2020-02-01' and y=145. The location of the text can also be shifted using ax=-20 and ay=-30, as an example.

Tip: multiple annotations can be layered on the graph by adding fig.add_annotation object.

STEP 6: Add an annotation with vertical lines

Tip: the line type may be adjusted by using these options:

Tip: multiple reference lines can be added using fig.update_layout(shapes=... and the lines can be added as a dictionary.

STEP 7: Add vertical & horizontal rectangle highlight sections

Tip: the horizontal and vertical highlight blocks can be created by adding an annotation section fig.add_hrect or fig.add_vrect. For the horizontal section, specify at which coordinates of y to place the blocks. The same can be done for the vertical highlight block, where x coordinates can be specified. The color of the highlight rectangle sections can be specified using the fillcolor option.

--

--