How to Add Text to Subplots in Matplotlib

You can use the following syntax to add text to specific subplots in Matplotlib:

import matplotlib.pyplot as plt

#define subplot layout
fig, ax = plt.subplots(2, 1, figsize=(7,4))

#add text at specific locations in subplots
ax[0].text(1.5, 20, 'Here is some text in the first subplot')
ax[1].text(2, 10, 'Here is some text in the second subplot')

This particular example adds text to the first subplot at the (x, y) coordinates (1.5, 20) and some text to the second subplot at the (x, y) coordinates (2, 10).

The following example shows how to use this syntax in practice.

Example: Add Text to Subplots in Matplotlib

The following code shows how to create two subplots in Matplotlib, arranged in a layout with two rows and one column:

import matplotlib.pyplot as plt

#define subplot layout
fig, ax = plt.subplots(2, 1, figsize=(7,4))
fig.tight_layout()

#define data
x = [1, 2, 3]
y = [7, 13, 24]

#create subplots
ax[0].plot(x, y, color='red')
ax[1].plot(x, y, color='blue')

We can use the following syntax to add text to specific locations on each subplot:

import matplotlib.pyplot as plt

#define subplot layout
fig, ax = plt.subplots(2, 1, figsize=(7,4))
fig.tight_layout()

#define data
x = [1, 2, 3]
y = [7, 13, 24]

#create subplots
ax[0].plot(x, y, color='red')
ax[1].plot(x, y, color='blue')

#add text at specific locations in subplots
ax[0].text(1.5, 20, 'Here is some text in the first subplot')
ax[1].text(2, 10, 'Here is some text in the second subplot')

Matplotlib add text to subplots

Notice that text has been added to each subplot at the (x, y) coordinates that we specified.

Note that we used ax[0] to reference the first subplot and ax[1] to reference the second subplot.

We then used the text() function to specify the (x, y) coordinates along with the specific text to use each in each subplot.

The following tutorials explain how to perform other common tasks in  Matplotlib:

 

x