Skip to content

Instantly share code, notes, and snippets.

@jonahpearl
Last active December 22, 2021 21:50
Show Gist options
  • Save jonahpearl/8e8ece0f289d51f4e7ff0e740add56e7 to your computer and use it in GitHub Desktop.
Save jonahpearl/8e8ece0f289d51f4e7ff0e740add56e7 to your computer and use it in GitHub Desktop.
Matplotlib scatter with categorical colors and a custom legend
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
clusters = np.random.randint(0,5, size=(x.shape[0],))
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
plt.scatter(x, y, c=[colors[c] for c in clusters])
plt.legend(handles=[Line2D([0],
[0],
marker='o',
color='w',
label=f'Cluster {c}',
markerfacecolor=colors[c],
markersize=10)
for c in range(len(np.unique(clusters)))],
fontsize=12,
loc='lower left')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment