return a dict of colors corresponding to the unique values
    
    :param values: values to be mapped
    :param cmap_name: colormap name
    :param alpha: color alpha
    :return: dict of colors corresponding to the unique values
960825
def create_set_cmap(values, cmap_name, alpha=255):
    
    unique_values = list(set(values))
    shuffle(unique_values)
    from pylab import get_cmap
    cmap = get_cmap(cmap_name)
    d = {}
    for i in range(len(unique_values)):
        d[unique_values[i]] = _convert_color_format(cmap(1.*i/len(unique_values)), alpha)
    return d
771939
def ginga_to_matplotlib_cmap(cm, name=None):
    """"""
    if name is None:
        name = cm.name
    from matplotlib.colors import ListedColormap
    carr = np.asarray(cm.clst)
    mpl_cm = ListedColormap(carr, name=name, N=len(carr))
    return mpl_cm
1008907
def get_colours(color_group, color_name, reverse=False):
    color_group = color_group.lower()
    cmap = get_map(color_group, color_name, reverse=reverse)
    return cmap.hex_colors
    
198651
def get_color_mode(mode):
    """"""
    name = mode.upper()
    name = name.rstrip('A')  # Trim alpha.
    name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name)
    return getattr(ColorMode, name)
115276
def get_color(self, value):
        
        if value in COLOR_SET:
            value = COLOR_MAP[value]
        else:
            try:
                value = int(value)
                if value >= 8:
                    raise ValueError()
            except ValueError as exc:
                raise ValueError(
                    'Colors should either a member of: {} or a positive '
                    'integer below 8'.format(', '.join(COLOR_NAMES))
                )
        return '{}{}'.format(self.PREFIX, value)
322108
def generateColorMap():
    '''
    
    '''
    Map = cm.jet(np.arange(256))
    stringColors = []
    for i in range(Map.shape[0]):
        rgb = (int(255*Map[i][0]), int(255*Map[i][1]), int(255*Map[i][2]))
        if (sys.version_info > (3, 0)):
            stringColors.append((struct.pack('BBB', *rgb).hex())) # python 3
        else:
            stringColors.append(
                struct.pack('BBB', *rgb).encode('hex'))  # python2

    return stringColors
1328477
def apply_color_map(name: str, mat: np.ndarray = None):
    """"""
    def apply_map(mat):
        return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
        
    return apply_map if mat is None else apply_map(mat)
136329
def make_colormap(seq):
    
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)
142011
def toColor(val, colormap):
    """"""
    for i in range(0, len(colormap) - 1):
        if colormap[i + 1][0] > val:
            scale = (val - colormap[i][0]) / \
                (colormap[i + 1][0] - colormap[i][0])
            r = colormap[i][1][0] + \
                (colormap[i + 1][1][0] - colormap[i][1][0]) * scale
            g = colormap[i][1][1] + \
                (colormap[i + 1][1][1] - colormap[i][1][1]) * scale
            b = colormap[i][1][2] + \
                (colormap[i + 1][1][2] - colormap[i][1][2]) * scale
            return "#" + toHex(r) + toHex(g) + toHex(b)
    return "#" + toHex(colormap[-1][1][0]) + toHex(colormap[-1][1][1]) + toHex(colormap[-1][1][2])
105992
def create_colormap(palette):
    """"""
    from trollimage.colormap import Colormap
    fname = palette.get('filename', None)
    if fname:
        data = np.load(fname)
        cmap = []
        num = 1.0 * data.shape[0]
        for i in range(int(num)):
            cmap.append((i / num, (data[i, 0] / 255., data[i, 1] / 255.,
                                   data[i, 2] / 255.)))
        return Colormap(*cmap)

    colors = palette.get('colors', None)
    if isinstance(colors, list):
        cmap = []
        values = palette.get('values', None)
        for idx, color in enumerate(colors):
            if values:
                value = values[idx]
            else:
                value = idx / float(len(colors) - 1)
            cmap.append((value, tuple(color)))
        return Colormap(*cmap)

    if isinstance(colors, str):
        from trollimage import colormap
        import copy
        return copy.copy(getattr(colormap, colors))

    return None
566447
def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0):
    
    result = dict()

    # TODO: The need to do this and the complexity of managing this kind of
    # thing throughout the codebase really suggests that we need to have
    # a real stylesheet class, where defaults and Types can declaratively
    # substitute for this kind of imperative logic.
    color = kwargs.pop(prefix + "color", get_default_color())
    for argname in ("fill_color", "line_color"):
        if argname not in glyphclass.properties():
            continue
        result[argname] = kwargs.pop(prefix + argname, color)

    # NOTE: text fill color should really always default to black, hard coding
    # this here now until the stylesheet solution exists
    if "text_color" in glyphclass.properties():
        result["text_color"] = kwargs.pop(prefix + "text_color", "black")

    alpha = kwargs.pop(prefix + "alpha", default_alpha)
    for argname in ("fill_alpha", "line_alpha", "text_alpha"):
        if argname not in glyphclass.properties():
            continue
        result[argname] = kwargs.pop(prefix + argname, alpha)

    return result
216057
def assign_style_props(df, color=None, marker=None, linestyle=None,
                       cmap=None):
    
    if color is None and cmap is not None:
        raise ValueError('`cmap` must be provided with the `color` argument')

    # determine color, marker, and linestyle for each line
    n = len(df[color].unique()) if color in df.columns else \
        len(df[list(set(df.columns) & set(IAMC_IDX))].drop_duplicates())
    defaults = default_props(reset=True, num_colors=n, colormap=cmap)

    props = {}
    rc = run_control()

    kinds = [('color', color), ('marker', marker), ('linestyle', linestyle)]

    for kind, var in kinds:
        rc_has_kind = kind in rc
        if var in df.columns:
            rc_has_var = rc_has_kind and var in rc[kind]
            props_for_kind = {}

            for val in df[var].unique():
                if rc_has_var and val in rc[kind][var]:
                    props_for_kind[val] = rc[kind][var][val]
                    # cycle any way to keep defaults the same
                    next(defaults[kind])
                else:
                    props_for_kind[val] = next(defaults[kind])
            props[kind] = props_for_kind

    # update for special properties only if they exist in props
    if 'color' in props:
        d = props['color']
        values = list(d.values())
        # find if any colors in our properties corresponds with special colors
        # we know about
        overlap_idx = np.in1d(values, list(PYAM_COLORS.keys()))
        if overlap_idx.any():  # some exist in our special set
            keys = np.array(list(d.keys()))[overlap_idx]
            values = np.array(values)[overlap_idx]
            # translate each from pyam name, like AR6-SSP2-45 to proper color
            # designation
            for k, v in zip(keys, values):
                d[k] = PYAM_COLORS[v]
            # replace props with updated dict without special colors
            props['color'] = d
    return props
1006860
def _build_color_variants(cls):
    
    # Get the basic frame types first.
    frametypes = cls.sets(registered=False)

    _colornames = [
        # 'black', disabled for now, it won't show on my terminal.
        'red',
        'green',
        'yellow',
        'blue',
        'magenta',
        'cyan',
        'white',
    ]
    _colornames.extend('light{}'.format(s) for s in _colornames[:])
    for colorname in _colornames:
        for framesobj in frametypes:
            framename = '{}_{}'.format(framesobj.name, colorname)
            cls.register(
                framesobj.as_colr(fore=colorname),
                name=framename,
            )
205342
def hue_sat_to_cmap(hue, sat):
    
    import colorsys

    # normalize to floats
    hue = float(hue) / 360.0
    sat = float(sat) / 100.0

    res = []
    for val in range(256):
        hsv_val = float(val) / 255.0
        r, g, b = colorsys.hsv_to_rgb(hue, sat, hsv_val)
        res.append((r, g, b))

    return res
1250900
def _match_cmap(self, fitsimage, colorbar):
        
        rgbmap = fitsimage.get_rgbmap()
        loval, hival = fitsimage.get_cut_levels()
        colorbar.set_range(loval, hival)
        # If we are sharing a ColorBar for all channels, then store
        # to change the ColorBar's rgbmap to match our
        colorbar.set_rgbmap(rgbmap)
1273813
def _get_color_values(adata, value_to_plot, groups=None, palette=None, use_raw=False,
                      gene_symbols=None, layer=None):
    

    ###
    # when plotting, the color of the dots is determined for each plot
    # the data is either categorical or continuous and the data could be in
    # 'obs' or in 'var'
    categorical = False
    if value_to_plot is None:
        color_vector = 'lightgray'
    # check if value to plot is in obs
    elif value_to_plot in adata.obs.columns:
        if is_categorical_dtype(adata.obs[value_to_plot]):
            categorical = True

            if palette:
                # use category colors base on given palette
                _set_colors_for_categorical_obs(adata, value_to_plot, palette)
            else:
                if value_to_plot + '_colors' not in adata.uns or \
                    len(adata.uns[value_to_plot + '_colors']) < len(adata.obs[value_to_plot].cat.categories):
                    #  set a default palette in case that no colors or few colors are found
                    _set_default_colors_for_categorical_obs(adata, value_to_plot)
                else:
                    # check that the colors in 'uns' are valid
                    _palette = []
                    for color in adata.uns[value_to_plot + '_colors']:
                        if not is_color_like(color):
                            # check if the color is a valid R color and translate it
                            # to a valid hex color value
                            if color in utils.additional_colors:
                                color = utils.additional_colors[color]
                            else:
                                logg.warn("The following color value found in adata.uns['{}'] "
                                          " is not valid: '{}'. Default colors are used.".format(value_to_plot + '_colors', color))
                                _set_default_colors_for_categorical_obs(adata, value_to_plot)
                                _palette = None
                                break
                        _palette.append(color)
                    if _palette is not None:
                        adata.uns[value_to_plot + '_colors'] = _palette
            # for categorical data, colors should be
            # stored in adata.uns[value_to_plot + '_colors']
            # Obtain color vector by converting every category
            # into its respective color

            color_vector = [adata.uns[value_to_plot + '_colors'][x] for x in adata.obs[value_to_plot].cat.codes]
            if groups is not None:
                if isinstance(groups, str):
                    groups = [groups]
                color_vector = np.array(color_vector, dtype='<U15')
                # set color to 'light gray' for all values
                # that are not in the groups
                color_vector[~adata.obs[value_to_plot].isin(groups)] = "lightgray"
        else:
            color_vector = adata.obs[value_to_plot].values
    # when value_to_plot is not in adata.obs
    else:
        if gene_symbols is not None and gene_symbols in adata.var.columns:
            if value_to_plot not in adata.var[gene_symbols].values:
                logg.error("Gene symbol {!r} not found in given gene_symbols "
                           "column: {!r}".format(value_to_plot, gene_symbols))
                return
            value_to_plot = adata.var[adata.var[gene_symbols] == value_to_plot].index[0]
        if layer is not None and value_to_plot in adata.var_names:
            if layer not in adata.layers.keys():
                raise KeyError('Selected layer: {} is not in the layers list. The list of '
                               'valid layers is: {}'.format(layer, adata.layers.keys()))
            color_vector = adata[:, value_to_plot].layers[layer]
        elif use_raw and value_to_plot in adata.raw.var_names:
            color_vector = adata.raw[:, value_to_plot].X
        elif value_to_plot in adata.var_names:
            color_vector = adata[:, value_to_plot].X
        else:
            raise ValueError("The passed `color` {} is not a valid observation annotation "
                             "or variable name. Valid observation annotation keys are: {}"
                             .format(value_to_plot, adata.obs.columns))

    return color_vector, categorical
813770
def _get_cmaps(names):
    """"""
    import matplotlib.pyplot as plt
    available_cmaps = list(
        chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
    names = list(names)
    wrongs = []
    for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
                                         arg not in available_cmaps)):
        if isinstance(arg, str):
            similarkeys = get_close_matches(arg, available_cmaps)
        if similarkeys != []:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
        else:
            warn("Colormap %s not found in standard colormaps.\n"
                 "Run function without arguments to see all colormaps" % arg)
        names.remove(arg)
        wrongs.append(arg)
    if not names and not wrongs:
        names = sorted(m for m in available_cmaps if not m.endswith("_r"))
    return names