Matplotlib
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.
We will only give you a very brief introduction, and allow you to try things out on your own with a simple exercise. 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 to 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 we 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.
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 tired to prepare more guided materials, definitely not! 😆
We have provided you with an exercise on the next page with various tasks for you to do. So 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.