Skip to content
Home » matplotlib Part 4 – Multiple Axes

matplotlib Part 4 – Multiple Axes

Spread the love

In the previous part of the Matplotlib series we created a figure with an Axes object on it with three functions plotted. Here it is again:

In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# Here are the x values
x = np.linspace(-10, 10, 100)

# Here are the three functions.
y1 = x ** 2 - 2 * x + 3
y2 = 10 * np.sin(x)
y3 = 2 * x + 1

# Let's create the figure and an axis.
fig, ax = plt.subplots()

# Let's plot the three functions. We'll pass the red, green and blue colors to the functions and the labels
# that will later appear in the legend.
ax.plot(x, y1, color='red', label='y1(x)')
ax.plot(x, y2, color='green', label='y2(x)')
ax.plot(x, y3, color='blue', label='y3(x)')

# Let's add the names of the two axes (x and y).
ax.set_xlabel('x')
ax.set_ylabel('y')

# Finally, let's add the legend.
ax.legend()
Out[1]:
<matplotlib.legend.Legend at 0x1aae8a83488>

But what if we wanted each function to be plotted in its own coordinate space? Fortunately, we can add as many Axes as needed. Here we have three functions, so let’s use three Axes:

In [2]:
# The x values and the three functions are just like before.
x = np.linspace(-10, 10, 100)
y1 = x ** 2 - 2 * x + 3
y2 = 10 * np.sin(x)
y3 = 2 * x + 1

# Let's create the figure and the three axes. We want the axes to be in three rows and one column,
# so we must pass 3 and 1 as the arguments to the subplots method.
fig, axes = plt.subplots(3, 1)

# Here are the plots. We use the indices 0-2 for the three axes. We'll also add titles to the graphs.
axes[0].set_title('y1(x)')
axes[0].plot(x, y1, color='red')

axes[1].set_title('y2(x)')
axes[1].plot(x, y2, color='green')

axes[2].set_title('y3(x)')
axes[2].plot(x, y3, color='blue')
Out[2]:
[<matplotlib.lines.Line2D at 0x1aaebbacc48>]

Don’t worry about the appearance of the graphs for now. We’ll make them look much better later in the series.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

You can also watch the video version of this article:


Spread the love

Leave a Reply