ML – Python (IV) – Matplotlib

Continuing with the useful libraries we can find in the Python ecosystem, we have Matplotlib. It is a library that will help us present our data. It is a 2D graphics library.

With Matplotlib, we can use both Python or NumPy data structures but, it seems recommendable to use the NumPy data structures.

In the same way that the previous library we saw, Matplotlib does not come with the default installation and we need to install it in our system.

Installing Matplotlib

The installation is as simple as executing a command:

pip install -U matplotlib

After that, we will be able to draw some nice plots. As an example we can draw a basic one:

import matplotlib.pyplot as plt

a = [1, 2, 3, 4]
b = [11, 22, 33, 44]

plt.plot(a, b, color='blue', linewidth=3, label='line')
plt.legend()
plt.show()

You can find the code example here.

The result should be something like:

Matplotlib basic example

Details about the result view

The resulting view, see picture above, can contain different elements:

  • The main object is the window or main page, it is the top-level object for the rest of the elements.
  • You can create multiple independent objects.
  • Objects can have subtitles, legends and colour bars among others.
  • We can generate areas within the objects. They are where the data is represented with methods like ‘plot()‘ or ‘scatter()‘ and they can have associated labels.
  • Every area has an X-axis and a Y-axis representing numerical values. They have a scale, title and labels among others.

Matplotlib package structure

  • Matplotlib: The whole Python data visualization package.
  • Pyplot: It is a module of the Matplotlib package. Provides an interface to create objects and axis.
  • Pylab: It is a module of the Matplolib package. It is used to work with matrices. Its use is not recommended any more with the new IDEs and kernels.

Most common plot types

The most common plot types we can find are:

You can see more examples of available plots here.

With this, we finish a short overview of Matplolib and the main plots it can offer to us. Very interesting to draw them easily.

ML – Python (IV) – Matplotlib

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.