• 6 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.



J'ai tout compris !

Mis à jour le 04/10/2021

Create graphs with Matplotlib

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Matplotlib was created to help you generate graphs directly from Python. Over the years, Matplotlib has become a powerful library, compatible with many platforms, and capable of generating graphics in lots of different formats.

In this chapter, we will focus on using Matplotlib as a visualization tool in Jupyter Notebooks.

First, let's set up our working environment.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

Generate simple graphs

Let's start by looking at a simple example: plotting a function.

fig = plt.figure()
ax = plt.axes()

Figure vide
Empty Figure

The variable  fig  corresponds to a container that contains all objects (axes, labels, data, etc.). The axes correspond to the grid shown above, which will then contain the graph's data.

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));

Courbe de sinus
Sin curve

We could have simply typed plt.plot(x, np.sin(x)).

So, here is our very first plot. Not bad. While this plot is nice, it is not quite ready for use in a professional setting. There are many aesthetic elements that need to be changed including:

  • The font size

  • The color of the graph

  • Line style of the curve 

  • Excess white space

There are also some functional elements that need to be included:

  • A title

  • A legend 

  • Labels for axes 

Let's check out the code:

# Change default font size
plt.rcParams.update({'font.size': 15})
fig = plt.figure()
ax = plt.axes()
# Solid line, color specified by its name
plt.plot(x, np.sin(x - 0), color='blue', linestyle='solid', label='bleu')
# Short name for color, dashed line
plt.plot(x, np.sin(x - 1), color='g', linestyle='dashed', label='vert')
# Grayscale between 0 and 1, dashes and dots
plt.plot(x, np.sin(x - 2), color='0.75', linestyle='dashdot', label='gris')
# RGB color, dotted line
plt.plot(x, np.sin(x - 3), color='#FF0000', linestyle='dotted', label='rouge')
# Axis limits. Try also 'tight' and 'equal' to see their effect
plt.axis([-1, 11, -1.5, 1.5]);
# Labels
plt.title("Example of a graph")
# The legend is generated from the argument 'label' of 'plot'
# 'loc' specified the placement of the legend.
plt.legend(loc='lower left');
# Axis titles
ax = ax.set(xlabel='x', ylabel='sin(x)')
A more complex graph
A more complete graph

Visualize uncertainty

We have constructed a plot using properties of Matplotlib. Another aspect of plotting that we should be aware of is the degree of uncertainty associated with estimates. It is extremely important to take this into account not only when analyzing the data, but also when representing them. 

To visualize uncertainty, or in other words, to represent how confident we are in our estimation, we are going to use what we all error bars. 

Discrete data

In the case of discrete data, we often use error bars to represent the uncertainty inherent to each point's value. Often, the length of the bars matches the standard deviation of the empirical observations. Adding error bars is easy on Matplotlib!

x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)
plt.errorbar(x, y, yerr=dy, fmt='.k');
Les barres d'erreur
Error bars

Errorbar takes as argument the x-coordinates, y-coordinates and lengths of each bar (one bar per point)  yerr . Note the  fmt  argument. It allows you to choose the color (here black) and the shape of the markers on the graph in a really concise way.  Errorbar  also allows you to further customize the appearance of the graph. 

plt.errorbar(x, y, yerr=dy, fmt='o', color='black',
ecolor='lightgray', elinewidth=3, capsize=0);
Des barres d'erreur plus jolies
Different look for error bars

Customize your plots

There is one other topic I want to cover before we conclude this chapter, and that is the notion of styles. Up to this point, we have been constructing plots from the ground up, but you can actually use a set of preconfigured properties called styles.

To preview, let's print the first six styles that we have. To give you a preview of what the styles are, let's pass in one plot, and show how the style changes the representation of the plot. In the future, feel free to come back to this section to remind yourself how to perform a specific operation.

# Change the size of the figure
fig = plt.figure(figsize=(12,8))
for i in range(6):
# This is how you add subplots
plt.plot(x, y)
# This is how you write on a plot
plt.text(s=plt.style.available[i], x=5, y=2, color='red')
Exemples de stylesheet

The first argument of the  add_subplot  function is the number of lines in our graph table (here  3 ). The second is the number of columns (here  2 ). The third is the number of actual graphs, among the graphs in this table, that we want to draw (here  1 ).

We can also customize everything by hand.

x = np.random.randn(1000)
ax = plt.axes(facecolor='#E6E6E6')
# Display ticks underneath the axis
# White frame
plt.grid(color='w', linestyle='solid')
# Hide the frame
for spine in ax.spines.values():
# Hide the markers at the top and the right
# We can personalise the markers, and rotate them
marqueurs = [-3, -2, -1, 0, 1, 2, 3]
xtick_labels = ['A', 'B', 'C', 'D', 'E', 'F']
plt.xticks(marqueurs, xtick_labels, rotation=30)
# Change the color of markers
ax.tick_params(colors='gray', direction='out')
for tick in ax.get_xticklabels():
for tick in ax.get_yticklabels():
# Change the color of the edges
ax.hist(x, edgecolor='#E6E6E6', color='#EE6666');
Graphique personnalisé
A custom plot


  • Matplotlib allows you to generate presentation-ready graphs

  • Error bars are used to visualize uncertainty. 

  • The  style  function allows you to customize plots 

Exemple de certificat de réussite
Exemple de certificat de réussite