Introduction to Axes (or Subplots)#

Matplotlib Axes are the gateway to creating your data visualizations. Once an Axes is placed on a figure there are many methods that can be used to add data to the Axes. An Axes typically has a pair of Axis Artists that define the data coordinate system, and include methods to add annotations like x- and y-labels, titles, and legends.

../../../_images/anatomy.png

Anatomy of a Figure#

In the picture above, the Axes object was created with ax = fig.subplots(). Everything else on the figure was created with methods on this ax object, or can be accessed from it. If we want to change the label on the x-axis, we call ax.set_xlabel('New Label'), if we want to plot some data we call ax.plot(x, y). Indeed, in the figure above, the only Artist that is not part of the Axes is the Figure itself, so the axes.Axes class is really the gateway to much of Matplotlib's functionality.

Note that Axes are so fundamental to the operation of Matplotlib that a lot of material here is duplicate of that in Quick start guide.

Creating Axes#

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(3.5, 2.5),
                        layout="constrained")
# for each Axes, add an artist, in this case a nice label in the middle...
for row in range(2):
    for col in range(2):
        axs[row, col].annotate(f'axs[{row}, {col}]', (0.5, 0.5),
                            transform=axs[row, col].transAxes,
                            ha='center', va='center', fontsize=18,
                            color='darkgrey')
fig.suptitle('plt.subplots()')

(Source code, 2x.png, png)