Skip to content

Instantly share code, notes, and snippets.

@sashabaranov
Last active September 6, 2016 12:35
Show Gist options
  • Save sashabaranov/bd1cefbeb72d991a0e8a817d2171b590 to your computer and use it in GitHub Desktop.
Save sashabaranov/bd1cefbeb72d991a0e8a817d2171b590 to your computer and use it in GitHub Desktop.

Poor Man's Colormap

Colormap is a way to convert some value with given range to RGB color.

There are multiple colormaps available in matplotlib package.

If you don't want to bring matplotlib's numerous dependencies with you, here is a simple solution, based on matplotlib data:


_color_data = [
  # data from https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm.py
  # or https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/_cm_listed.py
]


def colors_for_list_of_values(values):
def colors_for_list_of_values(values):
    """
    For given list [val1, val2, ...]
    Returns list of hex-html colors ["#ABCDEF", ...]
    """

    min_val, max_val = min(values), max(values)
    val_to_index = float(len(_color_data)) / abs(max_val - min_val)

    colors = []
    for val in values:
        color = _color_data[int((val - min_val)  * val_to_index)]
        color = tuple(255 * c for c in color)
        color_hex = "#%02x%02x%02x" % color

        colors.append(color_hex)

    return colors

With this and bokeh's plot.quad you can plot heatmaps without matplotlib dependency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment