Python Friday #165: Figures and Axes in Matplotlib

One of the main concepts you need to understand early on with Matplotlib is the idea of figures and axes. Today we explore these terms and find out how we can create them in code.

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.

 

Definitions

An Axes is a single plot that visualises the data. It uses 2 Axis objects for 2D plots (X-axis, Y-axis) or 3 Axis objects for 3D plots (X-axis, Y-axis, Z-axis)). Whenever we talk about Axes, we mean the complete set of Axis objects and everything else that we need to visualize our data.

A Figure is the whole figure / graphic that we produce. It is a container that can contain multiple Axes and even other figures (as subfigures). We can create a Figure directly from plt.figure() without an Axes and add them later or we can use plt.subplots() to get a Figure with one or more Axes:

To keep those terms apart, I like to think of it as an image that would show up in a book and looks like this:

The figure with 4 axes each containing two axis.

 

Create a figure with 2 axes

When we want to create more than one axes, we can specify the numbers of rows and the numbers of columns we want:

The axes are in a tuple where we can give names to the different objects to access them later. When we reuse the data for the x and y values from the last post, we can create a plot that looks like this:

A figure with two axes where the first axes is blue and the second one green.

 

Create a figure with 4 axes or more

As with the two axes we can specify larger numbers for the columns and rows. If we do that, we get back a tuple of tuples, but otherwise it works the same way as with two axes:

If we run this code in JupyterLab, it will create this plot for us:

We now get a figure with 4 axes that have a different line colour.

 

Next

I hope this explanation helps with understanding the difference between the Axes, Axis and Figure objects of Matplotlib. Next week we explore ways to save our plots into various formats.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.