Skip to content
Home » matplotlib Part 3 – The Elements of A Graph

matplotlib Part 3 – The Elements of A Graph

Spread the love

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:

In [1]:
%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)
Out[1]:
[<matplotlib.lines.Line2D at 0x181c57bafc8>]

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):

In [2]:
# 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[2]:
<matplotlib.legend.Legend at 0x181c5dbbb08>

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.

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.

Here’s the video version of the article:


Spread the love
Tags:

Leave a Reply