Premiers pas
Installation et premier graphique
Matplotlib est le socle du tracé en Python. pyplot est l'interface à état (comme MATLAB). Appelez toujours plt.show() pour afficher la figure dans un script ; dans un notebook Jupyter, la figure s'affiche automatiquement à la fin d'une cellule.
# install
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
# a simple line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()Interface à état pyplot
L'interface pyplot imite MATLAB : chaque appel opère sur la figure/les axes « courants » suivis en interne. Elle est concise pour des tracés rapides mais devient confuse avec plusieurs subplots. Utilisez plt.gcf()/plt.gca() pour accéder aux objets figure/axes courants.
import matplotlib.pyplot as plt
# pyplot tracks the "current" figure and axes
plt.figure() # create a new figure
plt.plot([1, 2, 3], [4, 5, 2])
plt.title("State-based") # applies to the current axes
plt.xlim(0, 4)
plt.ylim(0, 6)
plt.show()
# plt.gcf() -> current figure, plt.gca() -> current axes
print(plt.gca())Figure et Axes (interface OO)
L'interface orientée objet (OO) est l'approche recommandée dès qu'on dépasse un seul graphique. Vous créez une Figure (le canevas entier) et un ou plusieurs Axes (graphiques individuels) et appelez des méthodes dessus. Elle passe proprement aux subplots, axes jumeaux et mises en page complexes.
import matplotlib.pyplot as plt
import numpy as np
# object-oriented interface: explicit Figure and Axes objects
fig, ax = plt.subplots() # fig is the canvas, ax is a single Axes
x = np.linspace(0, 5, 50)
ax.plot(x, x**2, label="x^2")
ax.plot(x, x**3, label="x^3")
ax.set_title("OO Interface")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()Imports et conventions courantes
plt est l'alias quasi universel de pyplot et np celui de NumPy — presque tous les tutoriels et bibliothèques les attendent. rcParams est le dictionnaire de configuration global : réglez-le une fois en haut d'un script pour fixer DPI, taille de police, taille de figure et bien d'autres défauts.
# the universal alias
import matplotlib.pyplot as plt
import numpy as np
# for the OO interface you often see
from matplotlib.figure import Figure
from matplotlib.axes import Axes
# set a global style once
plt.rcParams["figure.dpi"] = 100
plt.rcParams["font.size"] = 11
# inline backend in Jupyter (not needed in scripts)
# %matplotlib inlineBackends et plt.show()
Un backend rend la figure : les backends interactifs (TkAgg, Qt5Agg) ouvrent une fenêtre, les non interactifs (Agg) écrivent seulement des fichiers. Appelez matplotlib.use() avant d'importer pyplot. plt.show() bloque dans les scripts jusqu'à la fermeture des fenêtres ; dans Jupyter, %matplotlib inline intègre les figures dans le notebook.
import matplotlib
# list available backends
print(matplotlib.rcsetup.all_backends)
# force a backend (do this BEFORE importing pyplot)
# matplotlib.use("Agg") # non-interactive, for saving files
# matplotlib.use("TkAgg") # interactive Tk window
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
# plt.show() blocks until the window is closed
plt.savefig("out.png") # saving works without any GUI backendCourbes (plot)
Courbe simple
plt.plot(x, y) trace une ligne reliant les points (x, y) dans l'ordre. Si vous passez un seul tableau, il sert de y et x vaut par défaut 0..N-1. plt.grid(True) active/désactive les lignes de grille. Les points sont reliés dans l'ordre du tableau : pour une courbe lisse, triez d'abord x.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.5)
y = x * 2
plt.plot(x, y)
plt.title("y = 2x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()Plusieurs courbes
Chaque appel plt.plot() ajoute une nouvelle courbe aux axes courants et avance automatiquement le cycle de couleurs. Passez un label= à chacune pour que plt.legend() puisse les identifier. Matplotlib gère les limites d'axes automatiquement, en s'adaptant à la plus grande plage.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.plot(x, np.sin(x) + np.cos(x), label="sin+cos")
plt.legend()
plt.title("Trig Functions")
plt.show()Styles de ligne et marqueurs
La chaîne de format 'couleur+marqueur+style de ligne' (ex. 'ro--') est compacte mais hermétique. Préférez les arguments explicites color=, marker=, linestyle= pour un code lisible. Styles de ligne courants : '-' '--' ':' '-.'. Marqueurs courants : 'o' 's' '^' 'D' 'v' '+' 'x'.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 20)
# format string: [color][marker][linestyle]
plt.plot(x, x, "r-") # red solid line
plt.plot(x, x*2, "go--") # green circles, dashed
plt.plot(x, x*3, "bs:") # blue squares, dotted
plt.plot(x, x*4, "k^-.") # black triangles, dash-dot
# explicit kwargs (clearer, recommended)
plt.plot(x, x*5, color="purple", marker="D",
linestyle="-.", linewidth=2, markersize=6)Couleurs
Matplotlib accepte de nombreux formats de couleurs : noms ('red'), chaînes hex ('#FF8800'), tuples RGB(A), noms Tableau ('tab:blue'), références au cycle ('C0'..'C9') et niveaux de gris ('0.5'). 'C0' prend la première couleur du style courant, gardant les graphiques cohérents avec le cycle de couleurs.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
plt.plot(x, x, color="red") # named color
plt.plot(x, x+0.2, color="#FF8800") # hex RGB
plt.plot(x, x+0.4, color=(0.1, 0.8, 0.2))# RGB tuple 0-1
plt.plot(x, x+0.6, color="C0") # cycle color 0
plt.plot(x, x+0.8, color="tab:purple") # Tableau palette
# gray shorthand: a string of float in [0,1]
plt.plot(x, x+1.0, color="0.5") # mid gray
plt.show()Épaisseur, alpha et zorder
linewidth contrôle l'