Learn Matplotlib in One Article


To understand a problem, it is often necessary to visualize it. This is why every good engineer must master tools for creating graphs, and this is what we will learn to do in this article by discovering the Matplotlib package of Python.

What is Matplotlib?

Matplotlib is a package (i.e. a grouping of several modules) used to create Python graphics. Here are some examples of what you can create with Matplotlib :



As you can see, anything is possible! 3D graphics, maps, lines, points, gradients, colors... with Matplotlib, you have control over all the parameters you could imagine (up to the position of your legend) without bothering with a too complex syntax. So I suggest you put Excel in the garbage to discover without further ado how to generate such charts!

Generating Simple Graphs with matplotlib.pyplot

To create a graph with matplotlib, it is very simple. You just have to import a module called pyplot and use one of the following graph functions:
  • scatter(x, y) : displays a scatter plot between x and y
  • plot(x, y) : displays a line graph between x and y
  • hist(x): displays a histogram of x.
Demo with the scatter() function:

1
2
3
4
5
6
7
8
9
import numpy as np
import matplotlib.pyplot as plt
 
# Creating data
x = np.linspace(0, 10, 30)
y = np.sin(x)
 
plt.scatter(x, y)
plt.show() # displays the graph (optional in Jupyter)



This is fast and simple, ideal for examining a scatter plot or a mathematical function with a single line of code. To take it a step further, Matplotlib also gives you the ability to control the style of your graphics: color, line style, thickness, transparency, etc. Let's take a look at it right now.

Styling your Matplotlib graphics

To style your graphs, you just need to add some arguments to the plot() and scatter() functions. Among the most useful arguments, I advise you to remember :
  • c : graph color ('red', 'blue', 'black', etc...)
  • lw : line width (for line graphs)
  • ls : line style (for line graphs)
  • marker: point style (for scatter graphs)
  • alpha : line or point transparency
1
2
3
4
5
6
7
8
9
10
import numpy as np
import matplotlib.pyplot as plt
 
# Creating data
x = np.linspace(0, 10, 30)
y = np.sin(x)
 
plt.plot(x, y, c='blue', ls='--', lw=1, alpha=0.5)
plt.scatter(x, y, c='red', marker='+')
plt.show()


You notice that in the example above, we get the two graphs plot and scatter overlaid on each other. By default, Matplotlib overlays your graphs on a single figure, but you can separate these graphs by creating different sub-figures with a function called subplot.

Matplotlib subplot : Dividing your figure into several subfigures

The subplot() function allows you to divide a figure into several parts, thus creating a grid of sub-figures. To do this, you need to pass 3 numbers to this function. The number of rows in the grid, the number of columns in the grid, and the sub-figure to work on. We write: plt.subplot(#rows, #columns, sub-figure)

For example, here is a grid with 1 row and 2 columns:

1
2
3
4
5
6
7
8
plt.subplot(1, 2, 1) # 1 row, 2 columns, sub-figure 1
plt.plot(x, y, c='blue', ls='--', lw=1, alpha=0.5)
plt.scatter(x, y, c='red', marker='+')
 
plt.subplot(1, 2, 2# 1 row, 2 columns, sub-figure 2
plt.scatter(x, y, c='orange', marker='x')
 
plt.show()



The result seems a bit "compressed", so we need to define a larger figure to contain our two sub-figures. To do this, we need to start our code by defining the creation of a new figure and indicating the dimensions of this figure


1
2
3
4
5
6
7
8
9
10
plt.figure(figsize=(12, 3)) # Creating a figure 12 inches wide and 3 inches high
 
plt.subplot(1, 2, 1) # 1 row, 2 columns, sub-figure 1
plt.plot(x, y, c='blue', ls='--', lw=1, alpha=0.5)
plt.scatter(x, y, c='red', marker='+')
 
plt.subplot(1, 2, 2# 1 row, 2 columns, sub-figure 2
plt.scatter(x, y, c='orange', marker='x')
 
plt.show()


That' s pretty good! To finish with the creation of simple figures, it is necessary to see how to display titles, axes and legends to our figures!

Matplotlib : Titles, Axes, Legends

To create Titles, Axes, and Legends in Matplotlib, simply use the following functions on each of your figures or sub-figures:
  • plt.title() : adds a title to the figure
  • plt.xlabel() plt.ylabel() : adds axes to the figure
  • plt.lenged() : adds a legend (according to the label indicated in the plot() or scatter() function
1
2
3
4
5
6
7
8
9
10
11
12
13
x = np.linspace(-5, 5, 100)
 
# creating graphs
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
 
# beautifying the figure
plt.title('sin(x) and cos(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
 
plt.show()


I suggest you now to put all these concepts together by showing you the life cycle of a Matplotlib figure.

Matplotlib figure's life cycle

To do things right with Matplotlib, I recommend that you start by declaring the creation of a figure with plt.figure(), which gives you the opportunity to define the size of your figure

Then you can work on different subfigures within your figure with the subplot() function. On each sub-figure, you can overlay several graphs (lines, points, and others that you can discover here) and add titles, axes, and legends.

I also advise you to use the function plt.savefig('figure.png') if you want to automatically save your figure on your computer.

Here is a quick demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
x = np.linspace(-5, 5, 100)
 
# New figure
plt.figure(figsize=(8, 8))
 
# Subfigure 1
plt.subplot(2, 1, 1)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.title('sin(x) and cos(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
 
# Subfigure 2
plt.subplot(2, 1, 2)
plt.plot(x, np.sinh(x), label='sinh(x)', ls='--', alpha=0.8)
plt.plot(x, np.cosh(x), label='cosh(x)', ls='--', alpha=0.8)
plt.title('sinh(x) and cosh(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
 
# Displays the figure and saves it
plt.show()
plt.savefig('myfigure.png')


Advanced Matplotlib : Object Oriented Programming

Matplotlib also has an object-oriented interface that gives even more control over your graphs, such as sharing the same x-axis on 2 sub-figures. However, I don't recommend using this interface if you are a beginner with Matplotlib, and the tutorial you just followed will allow you to accomplish 99% of the graphs you could imagine.

For more information about matplotlib, I invite you to consult the documentation on the official website here.