Skip to content
Home » matplotlib Part 10 – Text Annotations

matplotlib Part 10 – Text Annotations

Spread the love

In the previous part of the Matplotlib series we were talking about the legend. Today we’ll learn how to add text annotations to the graph.

Let’s create a simple graph on which we will be able to demonstrate it:

In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-100, 100, 500)
y = np.sin(x) / x

fig, ax = plt.subplots(figsize=(15, 5))
ax.plot(x, y)
Out[1]:
[<matplotlib.lines.Line2D at 0x1124b3aa308>]

Now let’s add a couple labels to the graph. We can do it by means of the ax.text method. It takes a few arguments. The first two arguments are the X and Y coordinates of the lower left corner of the label. Then we pass the text of the label. We can also add some formatting by passing some more arguments. Anyway, let’s start with something very basic. We’ll add three labels to the graph:

In [2]:
fig, ax = plt.subplots(figsize=(15, 5))
ax.plot(x, y)

ax.text(2, .95, 'high')
ax.text(-25, -.25, 'local minimum')
ax.text(6, -.25, 'local minimum')
Out[2]:
Text(6, -0.25, 'local minimum')

You can style the text directly in the ax.text method. All you have to do is set the appropriate arguments:

In [3]:
fig, ax = plt.subplots(figsize=(15, 5))
ax.plot(x, y)

# This label should be centered horizontally (we use the ha argument to do that) and a bit bigger.
ax.text(0, .95, 'high', ha='center', size=20)

# This label should be right-aligned and displayed in green.
ax.text(-6, -.25, 'local minimum', ha='right', color='green')

# This label should be displayed in red. It should also be bigger.
ax.text(6, -.25, 'local minimum', size=15, color='red')
Out[3]:
Text(6, -0.25, 'local minimum')

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply