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]:
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]:
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]: