OOP in Python, part 16: Class structure in Matplotlib
MP 61: Understanding how the Figure and Axes classes are implemented.
Note: This post is part of a series about OOP in Python. The posts in this series (except for the first one) will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.
This has been a long series; it will wrap up over the next few posts. Part 17 will discuss composition, and Part 18 will most likely be a wrap-up post for the series.
Matplotlib has two interfaces, one object-based and one function-based. For anything beyond simple plots, it's recommended to use the class-based API. In this post we'll make a simple plot using the object-oriented interface, and then use that plot to explore Matplotlib's internal implementation.
Using Matplotlib's object-oriented API
As an example, let's focus on triangle numbers. An integer is a triangle number if the corresponding number of dots can be arranged in a triangle, like this:
Here's a simple plot of the first six triangle numbers, using the object-oriented API for Matplotlib:
import matplotlib.pyplot as plt # Generate data. triangle_nums = [1, 3, 6, 10, 15, 21] x_values = [1, 2, 3, 4, 5, 6] # Generate plot. fig, ax = plt.subplots() ax.scatter(x_values, triangle_nums) # Format plot. ax.set_title("Triangle Numbers") ax.set_xlabel("N") ax.set_ylabel("Nth Triangle Number") # Show plot. plt.show()
After defining the data, we call
plt.subplots(). Understanding this one line is the key to understanding Matplotlib's object-oriented interface:
fig, ax = plt.subplots()
plt.subplots() function returns two objects: a
Figure object, and an
Axes object. We'll inspect those in a moment, and then explore the Matplotlib codebase to see how those two classes are implemented. For now, just know that the
Figure object refers to the overall set of plots; it's designed to manage more than one plot. The
ax object refers to a single plot; the name
ax refers to a pair of axes.
ax object has a number of plotting methods available. Here we call
ax.scatter() to make a scatter plot. We then make a series of method calls that set the title, and label each axis. Finally, the call to
plt.show() displays the plot in an interactive viewer:
Now that we have a plot, let’s use it to explore the internal implementation of Matplotlib.
First, let’s take a look at the
subplots() function. The code for this function is in pyplot.py:
Keep reading with a 7-day free trial
Subscribe to Mostly Python to keep reading this post and get 7 days of free access to the full post archives.