Annotations
In data visualization, annotations have a major role in available information to the reader.
They can be used to:
- highlight specific points
- provide additional information
- simply explain the data in more depth
However, it can be quite technicaly challenging to customize annotations in matplotlib, especially if you want specific text highlighting such as word in bold, italic or colored differently.
Let's see how we can create nice annotations in a few examples.
Libraries
Default tools from matplotlib are unfortunately not enough to create nice annotations. We will use the highlight-text package that simplifies the process.
Keep in mind that it would have been possible to use the flexitext package that can do approximately the same thing.
And we will also need to load matplotlib and numpy libraries.
Simple annotation
When creating a plot with annotation in matplotlib, we mainly use 2 functions:
- annotate()
- text()
Concretely, the annotate() function allows to add a text at a specific position, with an arrow pointing to a specific point, while the text() function allows to add a text at a specific position, without any arrow.
Let's see how they behave with a concrete example:
Boldness and Italics
Thanks to the highlight_text package, it is possible to bold and italic tp a specific part of the text. This is what will make the annotation stand out from the rest of the text.
The syntax is that we have to put the part of the text that we want to highlight between < and >. Then, we use the highlight_textprops argument to specify the style of the selected part.
Background color
You can easily add a background color to your annotation by using the bbox argument. You can customize lots of parameters:
- facecolor is the color of the background
- edgecolor is the color of the border
- linewidth is the width of the border
- pad is the padding between the text and the border
Path effects
The path effect is a way to add a shadow to your text, and it's highly customizable! In highlight_text, it relies on matplotlib's PathEffects module.
With it, we can specify:
- linewidth is the width of the shadow
- foreground is the color of the shadow
- alpha is the transparency of the shadow
- and more! You can see the official matplotlib documentation for more information.
Going further
This post explains how to create nice annotations in matplotlib with the highlight_text package.
You might be interested in how to have different colors in annotations or how to add an image in a plot