Exemples de comment ajouter une légende pour un nuage de points avec matplotlib:
Ajouter une simple légende pour un nuage de points
Exemple de comment ajouter une légende pour un nuage de points de deux couleurs avec la fonction legend():

import matplotlib.pyplot as pltx = [1,2,3,4]y = [4,1,3,6]plt.scatter(x, y, c='coral', label='Class 1')x = [5,6,7,8]y = [1,3,5,2]plt.scatter(x, y, c='lightblue', label='Class 2')plt.legend()plt.title('Nuage de points avec Matplotlib')plt.xlabel('x')plt.ylabel('y')plt.savefig('ScatterPlot_09.png')plt.show()
Ajouter une légende en utilisant "Proxy artists"
Autre exemple en définissant une légende manuellement (voir Proxy artists):

import matplotlib.pyplot as pltimport matplotlib.patches as mpatchesimport numpy as npx = [1,2,3,4,5,6,7,8]y = [4,1,3,6,1,3,5,2]categories = np.array([0, 0, 0, 0, 1, 1, 1, 1])colormap = np.array(['#0b559f', '#89bedc'])plt.scatter(x, y, s=100, c=colormap[categories])pop_a = mpatches.Patch(color='#0b559f', label='Population A')pop_b = mpatches.Patch(color='#89bedc', label='Population B')plt.legend(handles=[pop_a,pop_b])plt.title('Nuage de points avec Matplotlib')plt.xlabel('x')plt.ylabel('y')plt.savefig('ScatterPlot_10.png')plt.show()
Références
| Liens | Site |
|---|---|
| Matplotlib scatter plot legend | stackoverflow |
| Matplotlib scatter plot with legend | stackoverflow |
| shapes_and_collections example code: scatter_demo.py | matplotlib doc |
| Proxy artists | matplotlib doc |
