This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 9: Matplotlib

Matplotlib

face Josiah Wang

Matplotlib is a visualisation library for Python. It allows you to easily plot graphs, charts, figures, etc. Take a look at a sample of things you can do with Matplotlib.

I will only give you a very brief introduction, and allow you to try things out on your own with a series of simple exercises. You can then explore even more by referring to the official guide.

To use Matplotlib:

import matplotlib.pyplot as plt

Matplotlib draws your graphs on Figures, and each figure can contain one or more Axes (area where you can draw on). You do not usually need to explicitly create an Axes - this is usually done automatically.

If you are familiar with MATLAB, then matplotlib.pyplot are just a bunch of tools that provides MATLAB like plotting capabilities.

One of the things that you will likely have to do is to create a Figure. You can give a number as an argument to plt.figure() as an ID, which will be useful if you want to draw multiple figures. Otherwise, matplotlib will just create a new Figure.

fig = plt.figure(1)

Let’s say you want to plot a linear function. Here’s how you plot a line.

x = np.array([1, 2, 3, 4, 5])
y = x * 2
plt.plot(x, y)

You will also need to show() the figure to render it.

plt.show()

You should get a Figure similar to the one below.

Matplotlib example

Now, over to you! It is probably better for you to learn to use matplotlib by getting your hands dirty and trying things out for yourself, and finding out how to do things as you need them.

There is no point for me to create yet another guided tutorial on Matplotlib, especially since the official ones are already extensive and probably better than what I can produce. And I’m not saying this because I’m too lazy to prepare more learning materials, definitely not! 😆

I have provided you with a bunch of exercises on the next pages with various tasks for you to do. Try to solve the problems by checking out the official tutorials, documentation or just plain Googling. You will find that it is a better use of your time than just reading about all the features of Matplotlib. By the end of it, you should be able to grasp the basics of Matplotlib.