Exercice 37 / 100

Matplotlib - courbe

Tracez la courbe y = x² pour x de -10 à 10

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 plt

En 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

Pipeline classique

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()
Le trajet d'un graphique matplotlib : préparer les données, tracer la courbe, habiller le graphique, puis l'enregistrer dans un fichier

Exemple : tracer la parabole y = x²

import numpy as np import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 100) # 100 points entre -10 et 10 y = x ** 2
plt.plot(x, y) plt.title('Parabole') plt.xlabel('x') plt.ylabel('y') plt.grid(True) plt.savefig('/tmp/plot.png') print('Graphique sauvegardé')

Personnalisation rapide

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() vs plt.savefig()

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.

exercise.py

Envie d'aller plus loin ? Découvrez nos formations certifiées Bac+2 à Bac+5 →