Python Friday #171: Annotate Your Matplotlib Plots

Matplotlib can create a wide range of plots for us. But sometimes we need to point out an important aspect that only we know about. Let us figure out how we can do that.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Add horizontal lines

We can add a horizontal line with the axhline() method and add a descriptive text next to it with the annotate() method:

This gives us an orange dotted line with a “4” next to it:

A bar char with a line at the Y value of 4

In Matplotlib we do not need to calculate the location of our annotations and helper lines with an obscure pixel-based system. Instead, we use the same values as we do with our plot. That allows us to put annotations right at the place where we want them – and we could do that dynamically, like for an average value calculated from our dataset.

 

Add vertical lines

If we want to add a vertical line, we can use the axvline() method:

We now get green vertical line at the X-value 4 with a “Goal” label next to it:

A bar chart with a green line at the value 4 labelled as Goal

 

Add arrows

We can add arrows to our annotations with this code:

This gives us a red arrow with the text “Attention!” in magenta:

Our bar chart has now a red arrow that points to an important part

There are many other ways to add an arrow. If you need to create everything dynamically, you should check the arrow guide.

 

Next

Now we have everything together to draw on our diagrams and add annotations when we need to point out something important. Next week we will look at what happens when we combine several plots in the same figure.

1 thought on “Python Friday #171: Annotate Your Matplotlib Plots”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.