Skip to content

Instantly share code, notes, and snippets.

@ahwillia
Created February 18, 2021 23:36
Show Gist options
  • Save ahwillia/3e022cdd1fe82627cbf1f2e9e2ad80a7 to your computer and use it in GitHub Desktop.
Save ahwillia/3e022cdd1fe82627cbf1f2e9e2ad80a7 to your computer and use it in GitHub Desktop.
Simple formula for constructing a matplotlib colormap
from matplotlib.colors import LinearSegmentedColormap, colorConverter
def simple_cmap(colors, name='none'):
"""Create a colormap from a sequence of rgb values.
cmap = simple_cmap([(1,1,1), (1,0,0)]) # white to red colormap
cmap = simple_cmap(['w', 'r']) # white to red colormap
cmap = simple_cmap(['r', 'b', 'r']) # red to blue to red
"""
# check inputs
n_colors = len(colors)
if n_colors <= 1:
raise ValueError('Must specify at least two colors')
# convert colors to rgb
colors = [colorConverter.to_rgb(c) for c in colors]
# set up colormap
r, g, b = colors[0]
cdict = {'red': [(0.0, r, r)], 'green': [(0.0, g, g)], 'blue': [(0.0, b, b)]}
for i, (r, g, b) in enumerate(colors[1:]):
idx = (i+1) / (n_colors-1)
cdict['red'].append((idx, r, r))
cdict['green'].append((idx, g, g))
cdict['blue'].append((idx, b, b))
return LinearSegmentedColormap(name, {k: tuple(v) for k, v in cdict.items()})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment