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:
1 2 3 4 5 6 7 8 |
x = [1, 2, 3, 4] y = [7, 6, 1, 2] sla = 4 fig, ax = plt.subplots() ax.bar(x,y) ax.axhline(sla, linestyle=':', color='orange', linewidth=5) ax.annotate(f'{sla}', xy=(4.4, 4.1)) |
This gives us an orange dotted line with a “4” next to it:
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:
1 2 3 4 5 6 |
data = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6, 6] fig, ax = plt.subplots() ax.hist(data, bins=6) ax.axvline(4, linestyle=":", color="green") ax.annotate('Goal', xy=(4.05, 5.5), color="green") |
We now get green vertical line at the X-value 4 with a “Goal” label next to it:
Add arrows
We can add arrows to our annotations with this code:
1 2 3 4 5 6 7 8 9 10 |
x = [1, 2, 3, 4] y = [7, 6, 1, 2] sla = 4 fig, ax = plt.subplots() ax.bar(x,y) ax.annotate("Attention!", xy=(3, 1), xytext=(3.5, 4), color="magenta", arrowprops=dict(arrowstyle="->", color="red", linewidth=2, linestyle="-", hatch="x")) |
This gives us a red arrow with the text “Attention!” in magenta:
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”