Python matplotlib.colors.LinearSegmentedColormap.from_list() Examples

The following are 30 code examples of matplotlib.colors.LinearSegmentedColormap.from_list(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.colors.LinearSegmentedColormap , or try the search function .
Example #1
Source File: common.py    From typhon with MIT License 7 votes vote down vote up
def colors2cmap(*args, name=None):
    """Create a colormap from a list of given colors.

    Parameters:
        *args: Arbitrary number of colors (Named color, HEX or RGB).
        name (str): Name with which the colormap is registered.

    Returns:
        LinearSegmentedColormap.

    Examples:
        >>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
    """
    if len(args) < 2:
        raise Exception("Give at least two colors.")

    cmap_data = [_to_hex(c) for c in args]
    cmap = colors.LinearSegmentedColormap.from_list(name, cmap_data)
    plt.register_cmap(name, cmap)

    return cmap 
Example #2
Source File: colortable.py    From BasemapTutorial with Creative Commons Zero v1.0 Universal 7 votes vote down vote up
def read_color_table(color_file):
    '''
    The method for reading the color file.
    '''
    colors = []
    levels = []
    if exists(color_file) is False:
        raise Exception("Color file " + color_file + " does not exist")
    fp = open(color_file, "r")
    for line in fp:
        if line.find('#') == -1 and line.find('/') == -1:
            entry = line.split()
            levels.append(eval(entry[0]))
            colors.append((int(entry[1])/255.,int(entry[2])/255.,int(entry[3])/255.))
       
    fp.close()

    cmap = LinearSegmentedColormap.from_list("my_colormap",colors, N=len(levels), gamma=1.0)
    
    return levels, cmap 
Example #3
Source File: utils.py    From msmexplorer with MIT License 6 votes vote down vote up
def make_colormap(color_palette, N=256, gamma=1.0):
    """
    Create a linear colormap from a color palette.

    Parameters
    ----------

    color_palette : str, list, or dict
        A color string, list of color strings, or color palette dict

    Returns
    -------
    cmap : LinearSegmentedColormap
        A colormap object based on color_palette using linear segments.

    """
    colors = extract_palette(color_palette)
    rgb = map(hex2rgb, colors)
    return LinearSegmentedColormap.from_list('custom', list(rgb),
                                             N=N, gamma=1.0) 
Example #4
Source File: plot2d.py    From sfs-python with MIT License 6 votes vote down vote up
def _register_cmap_clip(name, original_cmap, alpha):
    """Create a color map with "over" and "under" values."""
    from matplotlib.colors import LinearSegmentedColormap
    cdata = _plt.cm.datad[original_cmap]
    if isinstance(cdata, dict):
        cmap = LinearSegmentedColormap(name, cdata)
    else:
        cmap = LinearSegmentedColormap.from_list(name, cdata)
    cmap.set_over([alpha * c + 1 - alpha for c in cmap(1.0)[:3]])
    cmap.set_under([alpha * c + 1 - alpha for c in cmap(0.0)[:3]])
    _plt.cm.register_cmap(cmap=cmap)


# The 'coolwarm' colormap is based on the paper
# "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland
# http://www.sandia.gov/~kmorel/documents/ColorMaps/ 
Example #5
Source File: util.py    From DLWP with MIT License 6 votes vote down vote up
def rgb_colormap(color='blue', size=100, reverse=False, white_padding=1, ):
    ll = size - white_padding
    clist = []
    r = 1
    g = 1
    b = 1
    if color == 'red':
        r = 0.5
    elif color == 'green':
        g = 0.5
    elif color == 'blue':
        b = 0.5
    else:
        raise ValueError('Select "red", "green", or "blue" for color.')
    for x in range(white_padding):
        clist.append([1.0, 1.0, 1.0])
    for x in range(white_padding, size, 1):
        y = x - white_padding
        clist.append([1.0 - 1.0 * r * y / ll, 1.0 - 1.0 * g * y / ll, 1.0 - 1.0 * b * y / ll])
    if reverse:
        clist = clist[::-1]

    cmap = LinearSegmentedColormap.from_list(color, clist)
    return cmap 
Example #6
Source File: util.py    From DLWP with MIT License 6 votes vote down vote up
def blue_red_colormap(size=100, reverse=False, white_padding=1, ):
    size = size - (size % 4)
    ll = size // 4
    clist = []
    s1 = [0.5 + 0.5 / ll * x for x in range(ll)]
    s2 = [1.0 / ll * x for x in range(ll)]
    for x in s1:
        clist.append([0.0, 0.0, x])
    for x in s2:
        clist.append([x, x, 1.0])
    for x in range(white_padding):
        clist.append([1.0, 1.0, 1.0])
    for x in range(ll):
        clist.append([1.0, s2[-x - 1], s2[-x - 1]])
    for x in range(ll):
        clist.append([s1[-x - 1], 0.0, 0.0])
    if reverse:
        clist = clist[::-1]

    from matplotlib.colors import LinearSegmentedColormap
    cmap = LinearSegmentedColormap.from_list('BuRd', clist)
    return cmap 
Example #7
Source File: misc.py    From emopt with GNU General Public License v3.0 6 votes vote down vote up
def get_dark_cmaps():
    """Generate dark-themed colormaps for eye-friendly visualization.

    Returns
    -------
    tuple
        Two matplotlib colormaps. The first color map is for +/- image data
        while the second is intended for strictly positive valued images.
    """
    from matplotlib.colors import LinearSegmentedColormap
    field_cols=['#3d9aff', '#111111', '#ff3d63']
    field_cmap=LinearSegmentedColormap.from_list('field_cmap', field_cols)

    struct_cols=['#212730', '#bcccdb']
    struct_cmap=LinearSegmentedColormap.from_list('struct_cmap', struct_cols)

    return field_cmap, struct_cmap 
Example #8
Source File: __init__.py    From e3sm_diags with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_colormap(colormap, parameters):
    """Get the colormap (string, list for vcs, or mpl colormap obj), which can be
    loaded from a local file in the cwd, installed file, or a predefined mpl/vcs one."""
    colormap = str(
        colormap)  # unicode don't seem to work well with string.endswith()
    if not colormap.endswith('.rgb'):  # predefined vcs/mpl colormap
        return colormap

    installed_colormap = os.path.join(acme_diags.INSTALL_PATH, 'colormaps', colormap)

    if os.path.exists(colormap):
        # colormap is an .rgb in the current directory
        pass
    elif not os.path.exists(colormap) and os.path.exists(installed_colormap):
        # use the colormap from /plot/colormaps
        colormap = installed_colormap
    elif not os.path.exists(colormap) and not os.path.exists(installed_colormap):
        pth = os.path.join(acme_diags.INSTALL_PATH, 'colormaps')
        msg = "File {} isn't in the current working directory or installed in {}"
        raise IOError(msg.format(colormap, pth))

    rgb_arr = numpy.loadtxt(colormap)
    rgb_arr = rgb_arr / 255.0

    if parameters.backend in ['cartopy', 'mpl', 'matplotlib']:
        cmap = LinearSegmentedColormap.from_list(name=colormap, colors=rgb_arr)
        return cmap

    elif parameters.backend in ['vcs']:
        n_levels = 240
        cmap = LinearSegmentedColormap.from_list(name=colormap, colors=rgb_arr, N=n_levels)
        vcs_cmap = matplotlib2vcs(cmap, vcs_name=colormap)

        return vcs_cmap, list(range(n_levels))

    else:
        raise RuntimeError('Invalid backend: {}'.format(parameters.backend)) 
Example #9
Source File: common.py    From typhon with MIT License 5 votes vote down vote up
def cmap2rgba(cmap=None, N=None, interpolate=True):
    """Convert a colormap into a list of RGBA values.

    Parameters:
        cmap (str): Name of a registered colormap.
        N (int): Number of RGBA-values to return.
            If ``None`` use the number of colors defined in the colormap.
        interpolate (bool): Toggle the interpolation of values in the
            colormap.  If ``False``, only values from the colormap are
            used. This may lead to the re-use of a color, if the colormap
            provides less colors than requested. If ``True``, a lookup table
            is used to interpolate colors (default is ``True``).

    Returns:
        ndarray: RGBA-values.

    Examples:
        >>> cmap2rgba('viridis', 5)
        array([[ 0.267004,  0.004874,  0.329415,  1.      ],
            [ 0.229739,  0.322361,  0.545706,  1.      ],
            [ 0.127568,  0.566949,  0.550556,  1.      ],
            [ 0.369214,  0.788888,  0.382914,  1.      ],
            [ 0.993248,  0.906157,  0.143936,  1.      ]])
    """
    cmap = plt.get_cmap(cmap)

    if N is None:
        N = cmap.N

    nlut = N if interpolate else None

    if interpolate and isinstance(cmap, colors.ListedColormap):
        # `ListedColormap` does not support lookup table interpolation.
        cmap = colors.LinearSegmentedColormap.from_list('', cmap.colors)
        return cmap(np.linspace(0, 1, N))

    return plt.get_cmap(cmap.name, lut=nlut)(np.linspace(0, 1, N)) 
Example #10
Source File: evaluation.py    From deepecg with MIT License 5 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, classes, figure_size=(8, 8)):
    """This function plots a confusion matrix."""
    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100

    # Build Laussen Labs colormap
    cmap = LinearSegmentedColormap.from_list('laussen_labs_green', ['w', '#43BB9B'], N=256)

    # Setup plot
    plt.figure(figsize=figure_size)

    # Plot confusion matrix
    plt.imshow(cm, interpolation='nearest', cmap=cmap)

    # Modify axes
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)
    thresh = cm.max() / 1.5
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, str(np.round(cm[i, j], 2)) + ' %', horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black", fontsize=20)
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    plt.tight_layout()
    plt.ylabel('True Label', fontsize=25)
    plt.xlabel('Predicted Label', fontsize=25)

    plt.show() 
Example #11
Source File: visualization.py    From GridCal with GNU General Public License v3.0 5 votes vote down vote up
def get_loading_color_map():
    """
    Loading Color map
    :return: colormap
    """
    load_max = 1.5
    seq = [(0.0 / load_max, 'gray'),
           (0.8 / load_max, 'green'),
           (1.2 / load_max, 'orange'),
           (1.5 / load_max, 'red')]
    loading_cmap = LinearSegmentedColormap.from_list('lcolors', seq)

    return loading_cmap 
Example #12
Source File: visualization.py    From GridCal with GNU General Public License v3.0 5 votes vote down vote up
def get_voltage_color_map():
    """
    Voltage Color map
    :return: colormap
    """
    vmax = 1.2
    seq = [(0 / vmax, 'black'),
           (0.8 / vmax, 'blue'),
           (1.0 / vmax, 'green'),
           (1.05 / vmax, 'orange'),
           (1.2 / vmax, 'red')]
    voltage_cmap = LinearSegmentedColormap.from_list('vcolors', seq)

    return voltage_cmap 
Example #13
Source File: common.py    From typhon with MIT License 5 votes vote down vote up
def cmap_from_act(file, name=None):
    """Import colormap from Adobe Color Table file.

    Parameters:
        file (str): Path to act file.
        name (str): Colormap name. Defaults to filename without extension.

    Returns:
        LinearSegmentedColormap.
    """
    # Extract colormap name from filename.
    if name is None:
        name = os.path.splitext(os.path.basename(file))[0]

    # Read binary file and determine number of colors
    rgb = np.fromfile(file, dtype=np.uint8)
    if rgb.shape[0] >= 770:
        ncolors = rgb[768] * 2**8 + rgb[769]
    else:
        ncolors = 256

    colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255

    # Create and register colormap...
    cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors)
    plt.register_cmap(cmap=cmap)  # Register colormap.

    # ... and the reversed colormap.
    cmap_r = LinearSegmentedColormap.from_list(
            name + '_r', np.flipud(colors), N=ncolors)
    plt.register_cmap(cmap=cmap_r)

    return cmap 
Example #14
Source File: utils.py    From unsupervised-depthnet with MIT License 5 votes vote down vote up
def opencv_rainbow(resolution=1000):
    # Construct the opencv equivalent of Rainbow
    opencv_rainbow_data = (
        (0.000, (1.00, 0.00, 0.00)),
        (0.400, (1.00, 1.00, 0.00)),
        (0.600, (0.00, 1.00, 0.00)),
        (0.800, (0.00, 0.00, 1.00)),
        (1.000, (0.60, 0.00, 1.00))
    )

    return LinearSegmentedColormap.from_list('opencv_rainbow', opencv_rainbow_data, resolution) 
Example #15
Source File: plot.py    From VerticaPy with Apache License 2.0 5 votes vote down vote up
def gen_cmap():
	cm1 = LinearSegmentedColormap.from_list("vml", ["#FFFFFF", "#263133"], N = 1000)
	cm2 = LinearSegmentedColormap.from_list("vml", ["#FE5016", "#FFFFFF", "#263133"], N = 1000)
	return (cm1, cm2)
#---# 
Example #16
Source File: utils.py    From SC-SfMLearner-Release with GNU General Public License v3.0 5 votes vote down vote up
def opencv_rainbow(resolution=1000):
    # Construct the opencv equivalent of Rainbow
    opencv_rainbow_data = (
        (0.000, (1.00, 0.00, 0.00)),
        (0.400, (1.00, 1.00, 0.00)),
        (0.600, (0.00, 1.00, 0.00)),
        (0.800, (0.00, 0.00, 1.00)),
        (1.000, (0.60, 0.00, 1.00))
    )

    return LinearSegmentedColormap.from_list('opencv_rainbow', opencv_rainbow_data, resolution) 
Example #17
Source File: fractals.py    From scikit_tt with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot2d(matrix):
    """Plot 2-dimensional fractals.

    Parameters
    ----------
    matrix: ndarray
        2-dimensional binary tensor representing the fractal pattern
    """

    ax.imshow(matrix, cmap=LinearSegmentedColormap.from_list('_', ['1', '0.33']))
    plt.xlim(-0.5 - (1 / 3) * matrix.shape[0], -0.5 + (4 / 3) * matrix.shape[0])
    plt.axis('off') 
Example #18
Source File: table.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def heat_map(self, cmap='RdYlGn', vmin=None, vmax=None, font_cmap=None):
        if cmap is None:
            carr = ['#d7191c', '#fdae61', '#ffffff', '#a6d96a', '#1a9641']
            cmap = LinearSegmentedColormap.from_list('default-heatmap', carr)

        if isinstance(cmap, basestring):
            cmap = get_cmap(cmap)
        if isinstance(font_cmap, basestring):
            font_cmap = get_cmap(font_cmap)

        vals = self.actual_values.astype(float)
        if vmin is None:
            vmin = vals.min().min()
        if vmax is None:
            vmax = vals.max().max()
        norm = (vals - vmin) / (vmax - vmin)
        for ridx in range(self.nrows):
            for cidx in range(self.ncols):
                v = norm.iloc[ridx, cidx]
                if np.isnan(v):
                    continue
                color = cmap(v)
                hex = rgb2hex(color)
                styles = {'BACKGROUND': HexColor(hex)}
                if font_cmap is not None:
                    styles['TEXTCOLOR'] = HexColor(rgb2hex(font_cmap(v)))
                self.iloc[ridx, cidx].apply_styles(styles)
        return self 
Example #19
Source File: rt-heatmap.py    From pyrocore with GNU General Public License v2.0 5 votes vote down vote up
def heatmap(self, df, imagefile):
        """ Create the heat map.
        """
        import seaborn as sns
        import matplotlib.ticker as tkr
        import matplotlib.pyplot as plt
        from  matplotlib.colors import LinearSegmentedColormap

        sns.set()
        with sns.axes_style('whitegrid'):
            fig, ax = plt.subplots(figsize=(5, 11))  # inches

            cmax = max(df[self.args[2]].max(), self.CMAP_MIN_MAX)
            csteps = {
                0.0: 'darkred', 0.3/cmax: 'red', 0.6/cmax: 'orangered', 0.9/cmax: 'coral',
                1.0/cmax: 'skyblue', 1.5/cmax: 'blue', 1.9/cmax: 'darkblue',
                2.0/cmax: 'darkgreen', 3.0/cmax: 'green',
                (self.CMAP_MIN_MAX - .1)/cmax: 'palegreen', 1.0: 'yellow'}
            cmap = LinearSegmentedColormap.from_list('RdGrYl', sorted(csteps.items()), N=256)

            dataset = df.pivot(*self.args)

            sns.heatmap(dataset, mask=dataset.isnull(), annot=False, linewidths=.5, square=True, ax=ax, cmap=cmap,
                        annot_kws=dict(stretch='condensed'))
            ax.tick_params(axis='y', labelrotation=30, labelsize=8)
            # ax.get_yaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: x))
            plt.savefig(imagefile) 
Example #20
Source File: common.py    From typhon with MIT License 5 votes vote down vote up
def cmap_from_txt(file, name=None, N=-1, comments='%'):
    """Import colormap from txt file.

    Reads colormap data (RGB/RGBA) from an ASCII file.
    Values have to be given in [0, 1] range.

    Parameters:
        file (str): Path to txt file.
        name (str): Colormap name. Defaults to filename without extension.
        N (int): Number of colors.
            ``-1`` means all colors (i.e., the complete file).
        comments (str): Character to start comments with.

    Returns:
        LinearSegmentedColormap.
    """
    # Extract colormap name from filename.
    if name is None:
        name = os.path.splitext(os.path.basename(file))[0]

    # Read binary file and determine number of colors
    rgb = np.genfromtxt(file, comments=comments)
    if N == -1:
        N = np.shape(rgb)[0]

    if np.min(rgb) < 0 or np.max(rgb) > 1:
        raise Exception('RGB value out of range: [0, 1].')

    # Create and register colormap...
    cmap = LinearSegmentedColormap.from_list(name, rgb, N=N)
    plt.register_cmap(cmap=cmap)

    # ... and the reversed colormap.
    cmap_r = LinearSegmentedColormap.from_list(
            name + '_r', np.flipud(rgb), N=N)
    plt.register_cmap(cmap=cmap_r)

    return cmap 
Example #21
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=-1):
    """
    Truncates a standard matplotlib colourmap so
    that you can use part of the colour range in your plots.
    Handy when the colourmap you like has very light values at
    one end of the map that can't be seen easily.

    Arguments:
      cmap (:obj: `Colormap`): A matplotlib Colormap object. Note this is not
         a string name of the colourmap, you must pass the object type.
      minval (int, optional): The lower value to truncate the colour map to.
         colourmaps range from 0.0 to 1.0. Should be 0.0 to include the full
         lower end of the colour spectrum.
      maxval (int, optional): The upper value to truncate the colour map to.
         maximum should be 1.0 to include the full upper range of colours.
      n (int): Leave at default.

    Example:
       minColor = 0.00
       maxColor = 0.85
       inferno_t = truncate_colormap(_plt.get_cmap("inferno"), minColor, maxColor)
    """
    cmap = _plt.get_cmap(cmap)

    if n == -1:
        n = cmap.N
    new_cmap = _mcolors.LinearSegmentedColormap.from_list(
         'trunc({name},{a:.2f},{b:.2f})'.format(name=cmap.name, a=minval, b=maxval),
         cmap(_np.linspace(minval, maxval, n)))
    return new_cmap 
Example #22
Source File: __init__.py    From arviz with Apache License 2.0 5 votes vote down vote up
def _mpl_cm(name, colorlist):
    cmap = LinearSegmentedColormap.from_list(name, colorlist, N=256)
    register_cmap("cet_" + name, cmap=cmap) 
Example #23
Source File: data.py    From CNNArt with Apache License 2.0 5 votes vote down vote up
def colorize(self, prediction, colormap=np.array([[0, 1, 0], [1, 1, 0], [1, 0, 0]])):
        """Colorize for patient-plots."""
        artifact_colormap = LinearSegmentedColormap.from_list('artifact_map_colors', colormap, N=100) # green -> yellow -> red

        # pred_picture = artifact_colormap[(prediction*100).astype(int)]
        return artifact_colormap 
Example #24
Source File: distinguishable_colors.py    From dwave_networkx with Apache License 2.0 5 votes vote down vote up
def distinguishable_color_map(num_colors):
    # Creates a matplotlib Colormap with num_colors visually distinct colors.
    try:
        from matplotlib.colors import LinearSegmentedColormap
    except ImportError:
        raise ImportError("Matplotlib required for distinguishable_color_map()")
    return LinearSegmentedColormap.from_list('dist_colors', distinguishable_colors[:min(num_colors, 1000)], num_colors)


# Colors originally generated using:
# https://www.mathworks.com/matlabcentral/fileexchange/29702-generate-maximally-perceptually-distinct-colors 
Example #25
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def discrete_colourmap(N, base_cmap=None):
    """Creates an N-bin discrete colourmap from the specified input colormap.

    Author: github.com/jakevdp adopted by DAV

    Note: Modified so you can pass in the string name of a colourmap
        or a Colormap object.

    Arguments:
        N (int): Number of bins for the discrete colourmap. I.e. the number
            of colours you will get.
        base_cmap (str or Colormap object): Can either be the name of a colourmap
            e.g. "jet" or a matplotlib Colormap object
    """

    print(type(base_cmap))
    if isinstance(base_cmap, _mcolors.Colormap):
        base = base_cmap
    elif isinstance(base_cmap, str):
        base = _plt.cm.get_cmap(base_cmap)
    else:
        print("Colourmap supplied is of type: ", type(base_cmap))
        raise ValueError('Colourmap must either be a string name of a colormap, \
                         or a Colormap object (class instance). Please try again.')

    color_list = base(_np.linspace(0, 1, N))
    cmap_name = base.name + str(N)
    return base.from_list(cmap_name, color_list, N) 
Example #26
Source File: mixin_tests.py    From geoplot with MIT License 5 votes vote down vote up
def test_hue_init_cmap(self):
        # cmap is None: 'viridis' is used
        expected = self.create_huemixin()
        expected.kwargs['cmap'] = 'viridis'
        result = self.create_huemixin()
        result.kwargs['cmap'] = None
        expected.set_hue_values(supports_categorical=False)
        result.set_hue_values(supports_categorical=False)
        assert result.colors == expected.colors

        # cmap is the name of a colormap: its value is propogated
        huemixin = self.create_huemixin()
        huemixin.kwargs['cmap'] = 'jet'
        huemixin.set_hue_values(supports_categorical=False)
        assert huemixin.cmap.cmap.name == 'jet'

        # cmap is a Colormap instance: it is propogated
        # Colormap is an abstract class, LinearSegmentedColormap stands in as a test object 
        huemixin = self.create_huemixin()
        colors = [(215/255, 193/255, 126/255), (37/255, 37/255, 37/255)]
        cm = LinearSegmentedColormap.from_list('test_colormap', colors)
        huemixin.kwargs['cmap'] = cm
        huemixin.set_hue_values(supports_categorical=False)
        assert huemixin.cmap.cmap.name == 'test_colormap'

        # cmap is not None but hue is None: raise
        huemixin = self.create_huemixin()
        huemixin.kwargs['cmap'] = 'viridis'
        huemixin.kwargs['hue'] = None
        with pytest.raises(ValueError):
            huemixin.set_hue_values(supports_categorical=False) 
Example #27
Source File: swap_colors.py    From augur with GNU Affero General Public License v3.0 5 votes vote down vote up
def swap_colors(json_file_path):
    '''
    Switches out color ramp in meta.json files.
    Uses custom color ramp if provided and valid; otherwise falls back to nextstrain default colors.
    N.B.: Modifies json in place and writes to original file path.
    '''
    j = json.load(open(json_file_path, 'r'))
    color_options = j['color_options']

    for k,v in color_options.items():
        if 'color_map' in v:
            categories, colors = zip(*v['color_map'])

            ## Use custom colors if provided AND present for all categories in the dataset
            if custom_colors and all([category in custom_colors for category in categories]):
                colors = [ custom_colors[category] for category in categories ]

            ## Expand the color palette if we have too many categories
            elif len(categories) > len(default_colors):
                from matplotlib.colors import LinearSegmentedColormap, to_hex
                from numpy import linspace
                expanded_cmap = LinearSegmentedColormap.from_list('expanded_cmap', default_colors[-1], N=len(categories))
                discrete_colors = [expanded_cmap(i) for i in linspace(0,1,len(categories))]
                colors = [to_hex(c).upper() for c in discrete_colors]

            else: ## Falls back to default nextstrain colors
                colors = default_colors[len(categories)] # based on how many categories are present; keeps original ordering

            j['color_options'][k]['color_map'] = map(list, zip(categories, colors))

    json.dump(j, open(json_file_path, 'w'), indent=1) 
Example #28
Source File: utils.py    From SfmLearner-Pytorch with MIT License 5 votes vote down vote up
def opencv_rainbow(resolution=1000):
    # Construct the opencv equivalent of Rainbow
    opencv_rainbow_data = (
        (0.000, (1.00, 0.00, 0.00)),
        (0.400, (1.00, 1.00, 0.00)),
        (0.600, (0.00, 1.00, 0.00)),
        (0.800, (0.00, 0.00, 1.00)),
        (1.000, (0.60, 0.00, 1.00))
    )

    return LinearSegmentedColormap.from_list('opencv_rainbow', opencv_rainbow_data, resolution) 
Example #29
Source File: utils.py    From cc with MIT License 5 votes vote down vote up
def opencv_rainbow(resolution=1000):
    # Construct the opencv equivalent of Rainbow
    opencv_rainbow_data = (
        (0.000, (1.00, 0.00, 0.00)),
        (0.400, (1.00, 1.00, 0.00)),
        (0.600, (0.00, 1.00, 0.00)),
        (0.800, (0.00, 0.00, 1.00)),
        (1.000, (0.60, 0.00, 1.00))
    )

    return LinearSegmentedColormap.from_list('opencv_rainbow', opencv_rainbow_data, resolution) 
Example #30
Source File: heatmap.py    From heatmappy with MIT License 5 votes vote down vote up
def _cmap_from_image_path(img_path):
        img = Image.open(img_path)
        img = img.resize((256, img.height))
        colours = (img.getpixel((x, 0)) for x in range(256))
        colours = [(r/255, g/255, b/255, a/255) for (r, g, b, a) in colours]
        return LinearSegmentedColormap.from_list('from_image', colours)