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]:
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]:
Don’t worry about the appearance of the graphs for now. We’ll make them look much better later in the series.
You can also watch the video version of this article: