Examples of how to add a legend to a scatter plot in matplotlib:
Add a simple legend to a scatter plot
Using the pyplot function legend():
import matplotlib.pyplot as plt
x = [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()
Add a legend to a scatter plot using "Proxy artists"
Another example using Proxy artists):
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
x = [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()
References
Links | 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 |