In the previous part of the Matplotlib series we created a basic graph. It consists of a figure with just one axis on it. In this part we’ll add some elements to the graph so that it’s slightly less basic. Just as a reminder, let’s plot the graph again:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = x ** 2 - 2 * x + 3
fig, ax = plt.subplots()
ax.plot(x, y)
Now we will plot two more functions on the same graph, each in a different color. Additionally, we will add the labels for the two axes (here by axes I mean the X and Y axes of the coordinate system) and a legend. In the legend you will see the colors of the lines and the names of the functions they represent. Here’s the code (without the imports because it’s enough to import once per session):
# 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()
Now you can see the labels for the two axes, x and y, the graphs of the three functions in different colors and the legend. It looks much better than before. Naturally, there’s still quite a lot that we can tweak, and we will, but for the time being, in the next article, we’ll see how to add more Axes instances to the figure and plot each function is a separate one.
Here’s the video version of the article: