Skip to content
{{ message }}

Instantly share code, notes, and snippets.

# andrashann/cmap_map.py

Created Oct 17, 2020
Companion notebook to my article about population density and social distancing
 import matplotlib import numpy as np import matplotlib.pyplot as plt #https://scipy-cookbook.readthedocs.io/items/Matplotlib_ColormapTransformations.html def cmap_map(function, cmap): """ Applies function (which should operate on vectors of shape 3: [r, g, b]), on colormap cmap. This routine will break any discontinuous points in a colormap. """ cdict = cmap._segmentdata step_dict = {} # Firt get the list of points where the segments start or end for key in ('red', 'green', 'blue'): step_dict[key] = list(map(lambda x: x, cdict[key])) step_list = sum(step_dict.values(), []) step_list = np.array(list(set(step_list))) # Then compute the LUT, and apply the function to the LUT reduced_cmap = lambda step : np.array(cmap(step)[0:3]) old_LUT = np.array(list(map(reduced_cmap, step_list))) new_LUT = np.array(list(map(function, old_LUT))) # Now try to make a minimal segment definition of the new LUT cdict = {} for i, key in enumerate(['red','green','blue']): this_cdict = {} for j, step in enumerate(step_list): if step in step_dict[key]: this_cdict[step] = new_LUT[j, i] elif new_LUT[j,i] != old_LUT[j, i]: this_cdict[step] = new_LUT[j, i] colorvector = list(map(lambda x: x + (x, ), this_cdict.items())) colorvector.sort() cdict[key] = colorvector return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
to join this conversation on GitHub. Already have an account? Sign in to comment