Matplotlib est la bibliothèque historique de visualisation Python. On utilise pyplot, l'interface simple.
Installation : pip install matplotlib Import conventionnel :
import matplotlib.pyplot as pltEn environnement sans écran (serveur, script, exos d'évaluation), il faut désactiver l'interface graphique avant d'importer pyplot :
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
1. préparer les données (x et y)
2. plt.plot(x, y) pour tracer
3. ajouter titre, labels, grille
4. plt.savefig('fichier.png') ou plt.show()Exemple : tracer la parabole y = x²
import numpy as np
import matplotlib.pyplot as pltx = np.linspace(-10, 10, 100) # 100 points entre -10 et 10
y = x ** 2plt.plot(x, y)
plt.title('Parabole')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.savefig('/tmp/plot.png')
print('Graphique sauvegardé')plt.plot(x, y, color='red', linewidth=2, linestyle='--', marker='o')
plt.legend(['y = x²'])
plt.xlim(-5, 5)
plt.ylim(0, 50)plt.show() affiche dans une fenêtre (en interactif)
plt.savefig(f) sauvegarde dans un fichier (PNG, PDF, SVG selon l'extension)Appelle savefig avant show, sinon le buffer est vidé et savegarde une image blanche.
linspace(a, b, n) génère n points équidistants entre a et b (inclus). Idéal pour tracer une courbe lisse.
Envie d'aller plus loin ? Découvrez nos formations certifiées Bac+2 à Bac+5 →