Skip to content

Instantly share code, notes, and snippets.

@adamconkey
Created July 3, 2020 19:30
Show Gist options
  • Save adamconkey/0630cc20f7be1049ee26cd43d72082f8 to your computer and use it in GitHub Desktop.
Save adamconkey/0630cc20f7be1049ee26cd43d72082f8 to your computer and use it in GitHub Desktop.
Function to generate random RGB tuples using Seaborn color palettes.
import random
import seaborn as sns
def random_colors(n_colors, palette='hls', xkcd_colors=[]):
"""
Generates list of random RGB colors.
Args:
n_colors (int): Number of random colors to return.
palette: Seaborn palette to generate random colors from. Can be a
string identifying a palette (e.g. 'hls', 'husl', 'Set2'),
or a list of colors (e.g. ["#9b59b6", "#3498db", "#95a5a6"]).
xkcd_colors (list): List of string color names from the xkcd RGB color
names. Overrides 'palette' arg.
Returns:
colors (list): List of n_colors 3-tuples of RGB values.
Options for xkcd_colors: https://xkcd.com/color/rgb
Choosing Seaborn palettes: https://seaborn.pydata.org/tutorial/color_palettes.html
"""
if xkcd_colors:
palette = list(sns.xkcd_palette(xkcd_colors))
colors = list(sns.color_palette(palette, n_colors))
random.shuffle(colors)
return colors
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
def _plot_subplot(axis, points, colors, title):
axis.scatter(points[:,0], points[:,1], s=1000, c=colors)
axis.set_title(title)
axis.set_xticks([])
axis.xaxis.set_ticklabels([])
axis.set_yticks([])
axis.yaxis.set_ticklabels([])
points = np.random.random((20, 2))
hls_colors = random_colors(len(points))
set2_colors = random_colors(len(points), "Set2")
manual_colors = random_colors(len(points), ["#9b59b6", "#3498db", "#95a5a6",
"#e74c3c", "#34495e", "#2ecc71"])
xkcd_colors = random_colors(len(points), xkcd_colors=["windows blue", "amber", "faded green",
"dusty purple", "light red", "deep blue"])
fig, axes = plt.subplots(2, 2)
fig.set_size_inches(12, 12)
_plot_subplot(axes[0, 0], points, hls_colors, "HLS Palette")
_plot_subplot(axes[0, 1], points, set2_colors, "Set2 Palette")
_plot_subplot(axes[1, 0], points, manual_colors, "Manual Palette")
_plot_subplot(axes[1, 1], points, xkcd_colors, "XKCD Palette")
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment