Created
July 2, 2022 21:10
-
-
Save granttremblay/df3978830eb9472f5c7ab137208f5bb0 to your computer and use it in GitHub Desktop.
Make a discrete colormap from a continuous colormap
This file contains hidden or 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
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