KerryHalupka / custom_colormap

Code for generating custom Matplotlib colormaps from RGB or HEX values
13 stars 5 forks source link

Simplify code using `matplotlib.colors.to_rgb` instead hex_to_rgb and rgb_to_dec #1

Open SrMouraSilva opened 3 years ago

SrMouraSilva commented 3 years ago

In https://github.com/KerryHalupka/custom_colormap/blob/ed92bc5/generate_colormap.py#L37, you can just use

rgb_list = [mcolors.to_rgb(colour) for colour in hex_list]
SrMouraSilva commented 3 years ago

An alternative code

def generate_cmap(cmap_name: str, colours: 'List[str]', graduation:'List[float]|None'=None) -> 'LinearSegmentedColormap':
    '''
    Generates a LinearSegmentedColormap based in a list of colours in hexadecimal format
    creates and returns a color map that can be used in heat map figures.

    If graduation is not provided, colour map graduates linearly between each color in colours.
    If graduation is provided, each color in hex_list is mapped to the respective location in graduation. 

    @param cmap_name: Name of the LinearSegmentedColormap generated
    @param colours: Colours in hex code format
    @param graduation: Floats between 0 and 1 with same length as hex_list. Must start with 0 and end with 1.

    @return colour map
    '''
    rgb_colours = [mcolors.to_rgb(colour) for colour in colours]
    graduation = graduation if graduation is not None else np.linspace(0, 1, len(rgb_colours))

    segmentdata = dict()
    for i, key in enumerate(['red', 'green', 'blue']):
        segmentdata[key] = [(f, colour[i], colour[i]) for f, colour in zip(graduation, rgb_colours)]

    return mcolors.LinearSegmentedColormap(cmap_name, segmentdata=segmentdata, N=256)