Matplotlib - Codes Essentiels
1. Installation et importation
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
2. Création de graphiques simples
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Courbe Sinus")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()
3. Personnalisation des tracés
plt.plot(x, y, color="red", linestyle="--", linewidth=2, marker="o")
plt.grid(True)
plt.legend(["Sinus"])
plt.show()
4. Graphiques multiples (subplot)
plt.subplot(2, 1, 1) # 2 lignes, 1 colonne, 1er plot
plt.plot(x, np.sin(x), "r")
plt.subplot(2, 1, 2) # 2 lignes, 1 colonne, 2e plot
plt.plot(x, np.cos(x), "b")
plt.show()
5. Histogrammes et diagrammes en barres
data = np.random.randn(1000)
plt.hist(data, bins=30, color="blue", alpha=0.7)
plt.title("Histogramme")
plt.show()
labels = ["A", "B", "C", "D"]
values = [10, 20, 30, 40]
plt.bar(labels, values, color="green")
plt.show()
6. Graphiques en nuage de points
x = np.random.rand(100)
y = np.random.rand(100)
plt.scatter(x, y, color="purple", alpha=0.5)
plt.show()
7. Graphiques 3D
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap="viridis")
plt.show()
8. Sauvegarde des graphiques
plt.plot(x, y)
plt.savefig("graphique.png", dpi=300)
plt.show()