Skip to content

Instantly share code, notes, and snippets.

@granttremblay
Created July 2, 2022 21:10
Show Gist options
  • Save granttremblay/df3978830eb9472f5c7ab137208f5bb0 to your computer and use it in GitHub Desktop.
Save granttremblay/df3978830eb9472f5c7ab137208f5bb0 to your computer and use it in GitHub Desktop.
Make a discrete colormap from a continuous colormap
def cmap_discretize(cmap, N):
"""Return a discrete colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: number of colors.
"""
if type(cmap) == str:
cmap = get_cmap(cmap)
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N+1)
cdict = {}
for ki, key in enumerate(('red','green','blue')):
cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1)]
# Return colormap object.
return matplotlib.colors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment