Voici un cheat sheet Matplotlib complet qui résume les principales fonctions et fonctionnalités:
Configuration initiale
import matplotlib.pyplot as plt
import numpy as np
# Configuration du style
plt.style.use('ggplot') # Autres options: 'seaborn', 'fivethirtyeight', 'bmh'...
# Configuration des paramètres globaux
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Arial']
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['figure.figsize'] = (10, 6)
plt.rcParams['figure.dpi'] = 100
Création de figures et axes
# Méthode 1: Création implicite
plt.figure(figsize=(10, 6))
plt.plot([1, 2, 3], [4, 5, 6])
plt.title('Titre du graphique')
# Méthode 2 (recommandée): Création explicite
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Titre du graphique')
# Création de plusieurs sous-graphiques
fig, axes = plt.subplots(2, 3, figsize=(15, 8)) # 2 lignes, 3 colonnes
axes[0, 0].plot([1, 2, 3], [4, 5, 6])
axes[0, 1].scatter([1, 2, 3], [4, 5, 6])
# Avec GridSpec pour des dispositions complexes
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(2, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :2]) # Première ligne, 2 premières colonnes
ax2 = fig.add_subplot(gs[0, 2]) # Première ligne, dernière colonne
ax3 = fig.add_subplot(gs[1, :]) # Seconde ligne, toutes les colonnes
Types de graphiques de base
Lignes
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Graphique simple
plt.plot(x, y)
# Personnalisation des lignes
plt.plot(x, y, 'r-', label='Sinus') # 'r-' = ligne rouge
plt.plot(x, np.cos(x), 'b--', linewidth=2, label='Cosinus') # ligne bleue en pointillés
# Styles de lignes: '-', '--', '-.', ':'
# Couleurs: 'b'=bleu, 'g'=vert, 'r'=rouge, 'c'=cyan, 'm'=magenta, 'y'=jaune, 'k'=noir, 'w'=blanc
# Avec objets axes
fig, ax = plt.subplots()
ax.plot(x, y, color='#FF5733', linestyle='--', linewidth=2, marker='o',
markersize=5, markerfacecolor='white', label='Étiquette')
Nuage de points (Scatter)
# Nuage de points simple
plt.scatter(x, y)
# Personnalisation
plt.scatter(x, y, s=100, c=y, cmap='viridis', alpha=0.7, edgecolors='black')
# s: taille des points, c: couleur, cmap: palette de couleurs, alpha: transparence
# Avec objets axes
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=y, s=np.abs(y)*100, cmap='plasma')
fig.colorbar(scatter, ax=ax, label='Valeur Y')
Barres
categories = ['A', 'B', 'C', 'D', 'E']
values = [15, 34, 23, 13, 47]
# Barres verticales
plt.bar(categories, values, color='skyblue', edgecolor='navy')
# Barres horizontales
plt.barh(categories, values, color='lightgreen', edgecolor='darkgreen')
# Barres groupées
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots()
ax.bar(x - width/2, values, width, label='Série 1')
ax.bar(x + width/2, [10, 25, 30, 15, 40], width, label='Série 2')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
Histogrammes
# Données aléatoires
data = np.random.randn(1000)
# Histogramme simple
plt.hist(data, bins=30)
# Personnalisation
plt.hist(data, bins=30, density=True, alpha=0.7, color='skyblue',
edgecolor='black', histtype='bar', rwidth=0.85)
# Histogrammes multiples
fig, ax = plt.subplots()
ax.hist([np.random.normal(0, 1, 1000), np.random.normal(2, 1, 1000)],
bins=30, label=['Dist A', 'Dist B'], alpha=0.7)
ax.legend()
Boîtes à moustaches (Box plots)
# Données aléatoires
data = [np.random.normal(0, std, 100) for std in range(1, 5)]
# Box plot simple
plt.boxplot(data)
# Personnalisation
fig, ax = plt.subplots()
box = ax.boxplot(data, patch_artist=True, notch=True, labels=['Groupe 1', 'Groupe 2', 'Groupe 3', 'Groupe 4'])
# Personnalisation des couleurs
colors = ['lightblue', 'lightgreen', 'tan', 'pink']
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
Camemberts (Pie charts)
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# Camembert simple
plt.pie(sizes, labels=labels)
# Personnalisation
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, shadow=True,
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99'], explode=(0.1, 0, 0, 0))
ax.axis('equal') # Pour un cercle parfait
Surfaces (Fill)
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.sin(x) + 1
# Remplissage entre deux courbes
plt.fill_between(x, y1, y2, alpha=0.5, color='skyblue')
# Remplissage jusqu'à y=0
plt.fill_between(x, y1, 0, where=(y1 > 0), alpha=0.3, color='green')
plt.fill_between(x, y1, 0, where=(y1 < 0), alpha=0.3, color='red')
Cartes de chaleur (Heatmaps)
data = np.random.rand(10, 12)
# Carte de chaleur simple
plt.imshow(data, cmap='viridis')
plt.colorbar()
# Personnalisation
fig, ax = plt.subplots(figsize=(10, 8))
heatmap = ax.imshow(data, cmap='YlOrRd', interpolation='nearest')
cbar = fig.colorbar(heatmap, ax=ax)
cbar.set_label('Intensité')
# Avec annotation des valeurs
for i in range(data.shape[0]):
for j in range(data.shape[1]):
ax.text(j, i, f'{data[i, j]:.2f}', ha='center', va='center',
color='white' if data[i, j] > 0.5 else 'black')
Personnalisation avancée
Titres et étiquettes
fig, ax = plt.subplots()
ax.plot(x, y)
# Titres et étiquettes
ax.set_title('Titre principal', fontsize=16, fontweight='bold')
ax.set_xlabel('Axe X', fontsize=12)
ax.set_ylabel('Axe Y', fontsize=12)
# Titre de figure (au-dessus du graphique)
fig.suptitle('Titre de la figure', fontsize=18, y=0.98)
# Rotation des étiquettes
ax.set_xticklabels(labels, rotation=45, ha='right')
Grilles et limites des axes
# Grille
ax.grid(True, linestyle='--', alpha=0.7)
ax.grid(axis='y', linestyle='-', alpha=0.5) # Grille uniquement sur l'axe Y
# Limites des axes
ax.set_xlim([0, 10])
ax.set_ylim([-1, 1])
# Échelles logarithmiques
ax.set_xscale('log')
ax.set_yscale('log')
# Inversion d'un axe
ax.invert_yaxis()
Légendes
ax.legend(loc='best') # Options: 'upper left', 'lower right', etc.
# Légende personnalisée
ax.legend(loc='upper right', frameon=True, framealpha=0.8,
ncol=2, title='Légende')
Annotations
# Texte simple
ax.text(5, 0.5, 'Texte personnalisé', fontsize=12, ha='center', va='center')
# Flèche
ax.annotate('Valeur max', xy=(5, 0.8), xytext=(7, 0.5),
arrowprops=dict(facecolor='black', shrink=0.05, width=1.5))
# Zone surlignée
ax.axvspan(2, 4, alpha=0.2, color='green') # Zone verticale
ax.axhspan(-0.5, 0.5, alpha=0.2, color='yellow') # Zone horizontale
# Lignes de référence
ax.axvline(x=5, color='r', linestyle='--') # Ligne verticale
ax.axhline(y=0, color='k', linestyle='-') # Ligne horizontale
Colorbars
# Ajout d'une barre de couleur
scatter = ax.scatter(x, y, c=y, cmap='viridis')
cbar = fig.colorbar(scatter, ax=ax)
cbar.set_label('Valeurs')
# Personnalisation de la colorbar
cbar = fig.colorbar(scatter, ax=ax, orientation='horizontal', pad=0.2)
cbar.ax.set_title('Échelle de couleurs')
Double axes Y
fig, ax1 = plt.subplots()
# Premier axe Y
ax1.plot(x, y, 'b-')
ax1.set_xlabel('X')
ax1.set_ylabel('Y1', color='b')
ax1.tick_params(axis='y', colors='b')
# Second axe Y
ax2 = ax1.twinx()
ax2.plot(x, np.cos(x), 'r-')
ax2.set_ylabel('Y2', color='r')
ax2.tick_params(axis='y', colors='r')
Sous-graphiques inégaux
from matplotlib import gridspec
fig = plt.figure(figsize=(12, 8))
gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1], height_ratios=[1, 2])
ax1 = fig.add_subplot(gs[0, 0]) # en haut à gauche
ax2 = fig.add_subplot(gs[0, 1]) # en haut à droite
ax3 = fig.add_subplot(gs[1, :]) # bas (toute la largeur)
Graphiques 3D
from mpl_toolkits.mplot3d import Axes3D
# Surface 3D
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))
surf = ax.plot_surface(X, Y, Z, cmap='coolwarm', linewidth=0, antialiased=True)
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
# Nuage de points 3D
ax.scatter(X, Y, Z, c='r', marker='o')
# Ligne 3D
zline = np.linspace(0, 15, 100)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'gray')
Sauvegarde et affichage
# Affichage du graphique
plt.tight_layout() # Ajustement automatique des marges
plt.show()
# Sauvegarde dans différents formats
plt.savefig('graphique.png', dpi=300, bbox_inches='tight') # PNG
plt.savefig('graphique.pdf', format='pdf') # PDF
plt.savefig('graphique.svg', format='svg') # SVG vectoriel
Animations
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10))
return line,
ani = animation.FuncAnimation(fig, animate, frames=100, interval=50, blit=True)
ani.save('animation.gif', writer='pillow', fps=20)
Paramètres de style courants
Couleurs (en notation RGB hex)
couleurs = {
'bleu_principal': '#1f77b4',
'orange': '#ff7f0e',
'vert': '#2ca02c',
'rouge': '#d62728',
'violet': '#9467bd',
'marron': '#8c564b',
'rose': '#e377c2',
'gris': '#7f7f7f',
'jaune': '#bcbd22',
'turquoise': '#17becf'
}
Marqueurs
'o': cercle
's': carré
'^': triangle vers le haut
'v': triangle vers le bas
'<', '>': triangles gauche/droite
'D': diamant
'*': étoile
'+', 'x': plus, croix
'.': point
Styles de lignes
'-': ligne continue
'--': ligne tiretée
'-.': ligne alternant tirets et points
':': ligne pointillée
Palettes de couleurs (colormaps)
# Séquentiel (pour un seul paramètre qui augmente)
colormaps_seq = ['viridis', 'plasma', 'inferno', 'magma', 'cividis', 'Blues', 'Greens', 'Reds', 'YlOrBr']
# Divergent (pour données centrées autour d'une valeur moyenne)
colormaps_div = ['PiYG', 'PRGn', 'BrBG', 'RdBu', 'RdGy', 'coolwarm']
# Cyclique (pour données angulaires, périodiques)
colormaps_cyc = ['twilight', 'hsv', 'twilight_shifted']
# Qualitatif (pour catégories discrètes)
colormaps_qual = ['Pastel1', 'Pastel2', 'Paired', 'Set1', 'Set2', 'tab10', 'tab20']
Cette fiche de référence est idéale pour garder sous la main pendant vos travaux de visualisation. Elle contient les commandes les plus utilisées et peut être consultée rapidement quand vous avez besoin de vous rappeler une fonction ou un paramètre spécifique.