Last active
December 22, 2021 21:50
-
-
Save jonahpearl/8e8ece0f289d51f4e7ff0e740add56e7 to your computer and use it in GitHub Desktop.
Matplotlib scatter with categorical colors and a custom legend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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