Python matplotlib.cm.get_cmap() Examples

The following are code examples for showing how to use matplotlib.cm.get_cmap(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: keras-anomaly-detection   Author: chen0040   File: h2o_ecg_pulse_detection.py    MIT License 6 votes vote down vote up
def plot_bidimensional(model, test, recon_error, layer, title):
    bidimensional_data = model.deepfeatures(test, layer).cbind(recon_error).as_data_frame()

    cmap = cm.get_cmap('Spectral')

    fig, ax = plt.subplots()
    bidimensional_data.plot(kind='scatter',
                            x='DF.L{}.C1'.format(layer + 1),
                            y='DF.L{}.C2'.format(layer + 1),
                            s=500,
                            c='Reconstruction.MSE',
                            title=title,
                            ax=ax,
                            colormap=cmap)
    layer_column = 'DF.L{}.C'.format(layer + 1)
    columns = [layer_column + '1', layer_column + '2']
    for k, v in bidimensional_data[columns].iterrows():
        ax.annotate(k, v, size=20, verticalalignment='bottom', horizontalalignment='left')
    fig.canvas.draw()
    plt.show() 
Example 2
Project: kvae   Author: simonkamronn   File: plotting.py    MIT License 6 votes vote down vote up
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
    # https://matplotlib.org/examples/color/colormaps_reference.html
    patches = []
    for pos in var:
        if shape == 'c':
            patches.append(mpatches.Circle(pos, r))
        elif shape == 'r':
            patches.append(mpatches.RegularPolygon(pos, 4, r))
        elif shape == 's':
            patches.append(mpatches.RegularPolygon(pos, 6, r))

    colors = np.linspace(start_color, .9, len(patches))
    collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
    collection.set_array(np.array(colors))
    collection.set_clim(0, 1)
    return collection 
Example 3
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyplot.py    MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap) 
Example 5
Project: viewer-demo   Author: CCI-Tools   File: image.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, source_image, value_range=(0.0, 1.0), cmap_name=None, num_colors=256,
                 no_data_value=None, encode=False, format=None, tile_cache=None):
        """
        Constructor.

        :param source_image:
        :param value_range:
        :param cmap_name:
        :param num_colors:
        :param no_data_value: fill value which will be mapped
        :param encode:
        :param format:
        :return:
        """
        super().__init__(source_image, format=format, mode='RGBA', tile_cache=tile_cache)
        self._value_range = value_range
        self._cmap_name = cmap_name if cmap_name else 'jet'
        self._cmap = cm.get_cmap(self._cmap_name, num_colors)
        self._cmap.set_bad('k', 0)
        self._no_data_value = no_data_value
        self._encode = encode 
Example 6
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    MIT License 6 votes vote down vote up
def list_of_hex_colours(N, base_cmap):
    """
    Return a list of colors from a colourmap as hex codes

        Arguments:
            cmap: colormap instance, eg. cm.jet.
            N: number of colors.

        Author: FJC
    """
    cmap = _cm.get_cmap(base_cmap, N)

    hex_codes = []
    for i in range(cmap.N):
        rgb = cmap(i)[:3] # will return rgba, we take only first 3 so we get rgb
        hex_codes.append(_mcolors.rgb2hex(rgb))
    return hex_codes 
Example 7
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    MIT License 6 votes vote down vote up
def cmap_discretize(N, cmap):
    """Return a discrete colormap from the continuous colormap cmap.

    Arguments:
        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example:
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = _plt.get_cmap(cmap)
    colors_i = _np.concatenate((_np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = _np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in range(N+1) ]
    # Return colormap object.
    return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024) 
Example 8
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    MIT License 6 votes vote down vote up
def __init__(self, cmap, levels):

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

        self.N = self.cmap.N
        self.monochrome = self.cmap.monochrome
        self.levels = _np.asarray(levels)#, dtype='float64')
        self._x = self.levels
        self.levmax = self.levels.max()
        self.levmin = self.levels.min()
        self.transformed_levels = _np.linspace(self.levmin, self.levmax,
             len(self.levels)) 
Example 9
Project: ble5-nrf52-mac   Author: tomasero   File: test_colorbar.py    MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example 10
Project: ble5-nrf52-mac   Author: tomasero   File: pyplot.py    MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap) 
Example 11
Project: Computable   Author: ktraunmueller   File: pyplot.py    MIT License 6 votes vote down vote up
def set_cmap(cmap):
    """
    Set the default colormap.  Applies to the current image if any.
    See help(colormaps) for more information.

    *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
    the name of a registered colormap.

    See :func:`matplotlib.cm.register_cmap` and
    :func:`matplotlib.cm.get_cmap`.
    """
    cmap = cm.get_cmap(cmap)

    rc('image', cmap=cmap.name)
    im = gci()

    if im is not None:
        im.set_cmap(cmap)

    draw_if_interactive() 
Example 12
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 13
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 6 votes vote down vote up
def colorbar(mappable, cax=None, ax=None, **kw):
    """
    Create a colorbar for a ScalarMappable instance.

    Documentation for the pylab thin wrapper:
    %(colorbar_doc)s
    """
    import matplotlib.pyplot as plt
    if ax is None:
        ax = plt.gca()
    if cax is None:
        cax, kw = make_axes(ax, **kw)
    cax.hold(True)
    cb = Colorbar(cax, mappable, **kw)

    def on_changed(m):
        cb.set_cmap(m.get_cmap())
        cb.set_clim(m.get_clim())
        cb.update_bruteforce(m)

    cbid = mappable.callbacksSM.connect('changed', on_changed)
    mappable.colorbar = cb
    ax.figure.sca(ax)
    return cb 
Example 14
Project: neural-network-animation   Author: miloharper   File: test_colorbar.py    MIT License 6 votes vote down vote up
def _get_cmap_norms():
    """
    Define a colormap and appropriate norms for each of the four
    possible settings of the extend keyword.

    Helper function for _colorbar_extension_shape and
    colorbar_extension_length.
    """
    # Create a color map and specify the levels it represents.
    cmap = get_cmap("RdBu", lut=5)
    clevs = [-5., -2.5, -.5, .5, 1.5, 3.5]
    # Define norms for the color maps.
    norms = dict()
    norms['neither'] = BoundaryNorm(clevs, len(clevs) - 1)
    norms['min'] = BoundaryNorm([-10] + clevs[1:], len(clevs) - 1)
    norms['max'] = BoundaryNorm(clevs[:-1] + [10], len(clevs) - 1)
    norms['both'] = BoundaryNorm([-10] + clevs[1:-1] + [10], len(clevs) - 1)
    return cmap, norms 
Example 15
Project: PRISM   Author: 1313e   File: custom_boxes.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_box_value(self):
        """
        Returns the current colormap of the colormap box.

        Returns
        -------
        cmap : :obj:`~matplotlib.colors.Colormap` object
            The currently selected colormap.

        """

        # Obtain the value
        colormap = get_box_value(self.cmaps_box)

        # Convert to matplotlib colormap
        cmap = cm.get_cmap(colormap)

        # Return it
        return(cmap)

    # This function sets the value of this special box 
Example 16
Project: MDT   Author: robbert-harms   File: matplotlib_renderer.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _get_map_plot_options(self, map_name):
        cmap = get_cmap(self._get_map_attr(map_name, 'colormap', self._plot_config.colormap))

        masked_color = self._get_map_attr(map_name, 'colormap_masked_color', self._plot_config.colormap_masked_color)
        if masked_color is not None:
            cmap.set_bad(color=masked_color)

        output_dict = {'vmin': self._data_info.get_single_map_info(map_name).min(),
                       'vmax': self._data_info.get_single_map_info(map_name).max(),
                       'cmap': cmap}

        scale = self._get_map_attr(map_name, 'scale', Scale())
        if scale.use_max:
            output_dict['vmax'] = scale.vmax
        if scale.use_min:
            output_dict['vmin'] = scale.vmin

        return output_dict 
Example 17
Project: pyparadigm   Author: KnorrFG   File: extras.py    MIT License 5 votes vote down vote up
def apply_color_map(name: str, mat: np.ndarray = None, normalize = True):
    """returns an RGB matrix scaled by a matplotlib color map,
    if normalize is False the matrix must only have values in the range [0, 1]"""
    def apply_map(mat):
        if normalize:
            mat = _normalize(mat)
        return (cm.get_cmap(name)(mat) * 255).astype(np.uint8) 
        
    return apply_map if mat is None else apply_map(mat) 
Example 18
Project: scanorama   Author: brianhie   File: utils.py    MIT License 5 votes vote down vote up
def visualize_expr(X, coords, genes, viz_gene, image_suffix='.svg',
                   new_fig=True, size=1, viz_prefix='ve'):
    genes = [ gene.upper() for gene in genes ]
    viz_gene = viz_gene.upper()
    
    if not viz_gene.upper() in genes:
        sys.stderr.write('Warning: Could not find gene {}\n'.format(viz_gene))
        return
    
    image_fname = '{}_{}{}'.format(
        viz_prefix, viz_gene, image_suffix
    )

    # Color based on percentiles.
    x_gene = X[:, list(genes).index(viz_gene)].toarray()
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_gene)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 19
Project: scanorama   Author: brianhie   File: utils.py    MIT License 5 votes vote down vote up
def visualize_dropout(X, coords, image_suffix='.svg',
                      new_fig=True, size=1, viz_prefix='dropout'):
    image_fname = '{}{}'.format(
        viz_prefix, image_suffix
    )

    # Color based on percentiles.
    x_gene = np.array(np.sum(X != 0, axis=1))
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_prefix)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 20
Project: LaserTOF   Author: kyleuckert   File: colorbar.py    MIT License 5 votes vote down vote up
def on_mappable_changed(self, mappable):
        """
        Updates this colorbar to match the mappable's properties.

        Typically this is automatically registered as an event handler
        by :func:`colorbar_factory` and should not be called manually.

        """
        self.set_cmap(mappable.get_cmap())
        self.set_clim(mappable.get_clim())
        self.update_normal(mappable) 
Example 21
Project: widgyts   Author: data-exp-lab   File: colormaps.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_mpl_cmaps(self):
        """ Adds available colormaps from matplotlib."""
        colormaps = {}
        import matplotlib.cm as mplcm
        cmap_list =  mplcm.cmap_d.keys()
        for colormap in cmap_list:
            cmap = mplcm.get_cmap(colormap)
            vals = (cmap(np.mgrid[0.0:1.0:256j])*255).astype("uint8")
            # right now let's just flatten the arrays. Later we can
            # serialize each cmap on its own.
            table = vals.flatten().tolist()
            colormaps[colormap] = table
        return colormaps 
Example 22
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: colorbar.py    MIT License 5 votes vote down vote up
def get_cmap(self):
        """
        return the colormap
        """
        return self.cmap 
Example 23
Project: c3dpo_nrsfm   Author: facebookresearch   File: vis_utils.py    MIT License 5 votes vote down vote up
def visdom_plot_pointclouds(viz, pcl, visdom_env, title,
                            plot_legend=True, markersize=2,
                            nmax=5000, sticks=None, win=None):

    if sticks is not None:
        pcl = {k: extend_to_3d_skeleton_simple(v, sticks)[0]
               for k, v in pcl.items()}

    legend = list(pcl.keys())

    cmap = 'tab10'
    npcl = len(pcl)
    rgb = (cm.get_cmap(cmap)(np.linspace(0, 1, 10))
           [:, :3]*255.).astype(np.int32).T
    rgb = np.tile(rgb, (1, int(np.ceil(npcl/10))))[:, 0:npcl]

    rgb_cat = {k: np.tile(rgb[:, i:i+1], (1, p.shape[1])) for
               i, (k, p) in enumerate(pcl.items())}

    rgb_cat = np.concatenate(list(rgb_cat.values()), axis=1)
    pcl_cat = np.concatenate(list(pcl.values()), axis=1)

    if pcl_cat.shape[1] > nmax:
        with NumpySeedFix():
            prm = np.random.permutation(
                pcl_cat.shape[1])[0:nmax]
        pcl_cat = pcl_cat[:, prm]
        rgb_cat = rgb_cat[:, prm]

    win = viz.scatter(pcl_cat.T, env=visdom_env,
                      opts={'title': title, 'markersize': markersize,
                            'markercolor': rgb_cat.T}, win=win)
    # legend
    if plot_legend:
        dummy_vals = np.tile(
            np.arange(npcl)[:, None], (1, 2)).astype(np.float32)
        title = "%s_%s" % (title, legend)
        opts = dict(title=title, legend=legend, width=400, height=400)
        viz.line(dummy_vals.T, env=visdom_env, opts=opts)

    return win 
Example 24
Project: Learning2AdaptForStereo   Author: CVLAB-Unibo   File: preprocessing.py    Apache License 2.0 5 votes vote down vote up
def colorize_img(value, vmin=None, vmax=None, cmap=None):
    """
    A utility function for TensorFlow that maps a grayscale image to a matplotlib colormap for use with TensorBoard image summaries.
    By default it will normalize the input value to the range 0..1 before mapping to a grayscale colormap.
    Arguments:
      - value: 4D Tensor of shape [batch_size,height, width,1]
      - vmin: the minimum value of the range used for normalization. (Default: value minimum)
      - vmax: the maximum value of the range used for normalization. (Default: value maximum)
      - cmap: a valid cmap named for use with matplotlib's 'get_cmap'.(Default: 'gray')
    
    Returns a 3D tensor of shape [batch_size,height, width,3].
    """

    # normalize
    vmin = tf.reduce_min(value) if vmin is None else vmin
    vmax = tf.reduce_max(value) if vmax is None else vmax
    value = (value - vmin) / (vmax - vmin) # vmin..vmax

    # quantize
    indices = tf.to_int32(tf.round(value[:,:,:,0]*255))

    # gather
    color_map = cm.get_cmap(cmap if cmap is not None else 'gray')
    colors = color_map(np.arange(256))[:,:3]
    colors = tf.constant(colors, dtype=tf.float32)
    value = tf.gather(colors, indices)
    return value

###PER LOSS RIPROIEZIONE### 
Example 25
Project: KittiSeg   Author: MarvinTeichmann   File: seg_utils.py    MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output 
Example 26
Project: KittiSeg   Author: MarvinTeichmann   File: seg_utils.py    MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output 
Example 27
Project: KittiSeg   Author: MarvinTeichmann   File: seg_utils.py    MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output 
Example 28
Project: ehtplot   Author: liamedeiros   File: modify.py    GNU General Public License v3.0 5 votes vote down vote up
def pre(cname):
    return transform(get_ctab(get_cmap(cname))) 
Example 29
Project: ehtplot   Author: liamedeiros   File: ctab.py    GNU General Public License v3.0 5 votes vote down vote up
def get_ctab(cmap):
    if not isinstance(cmap, Colormap):
        cmap = get_cmap(cmap)
    return np.array([cmap(v) for v in np.linspace(0, 1, cmap.N)]) 
Example 30
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    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 31
Project: LSDMappingTools   Author: LSDtopotools   File: colours.py    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 32
Project: EvisionNet   Author: jiafeng5513   File: my_utils.py    MIT License 5 votes vote down vote up
def high_res_colormap(low_res_cmap, resolution=1000, max_value=1):
    # Construct the list colormap, with interpolated values for higer resolution
    # For a linear segmented colormap, you can just specify the number of point in
    # cm.get_cmap(name, lutsize) with the parameter lutsize
    x = np.linspace(0, 1, low_res_cmap.N)
    low_res = low_res_cmap(x)
    new_x = np.linspace(0, max_value, resolution)
    high_res = np.stack([np.interp(new_x, x, low_res[:, i]) for i in range(low_res.shape[1])], axis=1)
    return ListedColormap(high_res) 
Example 33
Project: EvisionNet   Author: jiafeng5513   File: my_utils.py    MIT License 5 votes vote down vote up
def high_res_colormap(low_res_cmap, resolution=1000, max_value=1):
    # Construct the list colormap, with interpolated values for higer resolution
    # For a linear segmented colormap, you can just specify the number of point in
    # cm.get_cmap(name, lutsize) with the parameter lutsize
    x = np.linspace(0, 1, low_res_cmap.N)
    low_res = low_res_cmap(x)
    new_x = np.linspace(0, max_value, resolution)
    high_res = np.stack([np.interp(new_x, x, low_res[:, i]) for i in range(low_res.shape[1])], axis=1)
    return ListedColormap(high_res) 
Example 34
Project: SfmLearner-Pytorch   Author: ClementPinard   File: utils.py    MIT License 5 votes vote down vote up
def high_res_colormap(low_res_cmap, resolution=1000, max_value=1):
    # Construct the list colormap, with interpolated values for higer resolution
    # For a linear segmented colormap, you can just specify the number of point in
    # cm.get_cmap(name, lutsize) with the parameter lutsize
    x = np.linspace(0,1,low_res_cmap.N)
    low_res = low_res_cmap(x)
    new_x = np.linspace(0,max_value,resolution)
    high_res = np.stack([np.interp(new_x, x, low_res[:,i]) for i in range(low_res.shape[1])], axis=1)
    return ListedColormap(high_res) 
Example 35
Project: PointCNN.MX   Author: chinakook   File: data_utils.py    MIT License 5 votes vote down vote up
def save_ply_property(points, property, property_max, filename, cmap_name='Set1'):
    point_num = points.shape[0]
    colors = np.full(points.shape, 0.5)
    cmap = cm.get_cmap(cmap_name)
    for point_idx in range(point_num):
        colors[point_idx] = cmap(property[point_idx] / property_max)[:3]
    save_ply(points, filename, colors) 
Example 36
Project: VNSIM   Author: ZhenZHAO   File: Func_gui.py    GNU General Public License v3.0 5 votes vote down vote up
def update_panel_img(self):
        gamma = 0.5
        colormap = cm.get_cmap(self.myData.var_color_map_name)

        # reset ui
        self.reset_panel_img()

        # draw new - src
        show_model, src_max = self.myData.get_data_img_model()
        x_range = self.myData.myFuncUv.get_max_uv() // 4
        model_plot = self.figs_img_fig_src.imshow(np.power(show_model, gamma), picker=True,
                                                  origin='lower', cmap=colormap, norm=norm)
        pl.setp(model_plot, extent=(-src_max / 2., src_max / 2., -src_max / 2., src_max / 2.))

        # draw new - beam
        show_beam, x_max = self.myData.get_data_img_beam()
        beam_plot = self.figs_img_fig_beam.imshow(show_beam, picker=True, origin='lower',
                                                  aspect='equal', cmap=colormap, norm=norm)
        pl.setp(beam_plot, extent=(-x_range / 2., x_range / 2., -x_range / 2., x_range / 2.))

        # draw new - dirty
        show_map, x_max = self.myData.get_data_img_dirty()
        dirty_plot = self.figs_img_fig_dirty.imshow(show_map, picker=True, origin='lower', aspect='equal',
                                                    cmap=colormap, norm=norm)
        pl.setp(dirty_plot, extent=(-x_range / 2., x_range / 2., -x_range / 2., x_range / 2.))

        # draw new - clean
        clean_img, res_img = self.myData.get_data_img_clean()
        clean_plot = self.figs_img_fig_clean.imshow(clean_img, picker=True, origin='lower', aspect='equal',
                                                    cmap=colormap, norm=norm)
        pl.setp(clean_plot, extent=(-x_range / 2., x_range / 2., -x_range / 2., x_range / 2.))

        # show new
        self.canvas_img.show()

    # radplot 
Example 37
Project: deblur-devil   Author: visinf   File: cmap.py    Apache License 2.0 5 votes vote down vote up
def get_cmap_as_float_array(cmap_name):
        raw_cmap = cm.get_cmap(cmap_name, 256)
        cmap_array = raw_cmap(np.arange(256))[:, 0:3]  # remove alpha channels
        return cmap_array 
Example 38
Project: MediumRare   Author: filipkny   File: Gridworld.py    MIT License 5 votes vote down vote up
def show_heatmap(best_q_mat, annot=True):
    # Hardcode our walls, treasure and snake_pit values
    for wall in walls:
        best_q_mat[wall[0], wall[1]] = None

    best_q_mat[treasure[0], treasure[1]] = None
    # best_q_mat[snake_pit[0], snake_pit[1]] = None
    cmap = get_cmap()
    ax = sns.heatmap(best_q_mat, annot=annot, linewidths=0.5, cmap=cmap)
    plt.show() 
Example 39
Project: MediumRare   Author: filipkny   File: Illustrator.py    MIT License 5 votes vote down vote up
def show_heatmap(self, treasure, walls, best_q_mat, annot=True):
        # Hardcode our walls, treasure and snake_pit values
        print(best_q_mat)
        for wall in walls:
            best_q_mat[wall[0], wall[1]] = None

        best_q_mat[treasure[0], treasure[1]] = None
        # best_q_mat[snake_pit[0], snake_pit[1]] = None
        cmap = get_cmap()
        ax = sns.heatmap(best_q_mat, annot=annot, linewidths=0.5, cmap=cmap)
        plt.show() 
Example 40
Project: ble5-nrf52-mac   Author: tomasero   File: colorbar.py    MIT License 5 votes vote down vote up
def on_mappable_changed(self, mappable):
        """
        Updates this colorbar to match the mappable's properties.

        Typically this is automatically registered as an event handler
        by :func:`colorbar_factory` and should not be called manually.

        """
        self.set_cmap(mappable.get_cmap())
        self.set_clim(mappable.get_clim())
        self.update_normal(mappable) 
Example 41
Project: ble5-nrf52-mac   Author: tomasero   File: test_colors.py    MIT License 5 votes vote down vote up
def test_colormap_endian():
    """
    Github issue #1005: a bug in putmask caused erroneous
    mapping of 1.0 when input from a non-native-byteorder
    array.
    """
    cmap = cm.get_cmap("jet")
    # Test under, over, and invalid along with values 0 and 1.
    a = [-0.5, 0, 0.5, 1, 1.5, np.nan]
    for dt in ["f2", "f4", "f8"]:
        anative = np.ma.masked_invalid(np.array(a, dtype=dt))
        aforeign = anative.byteswap().newbyteorder()
        assert_array_equal(cmap(anative), cmap(aforeign)) 
Example 42
Project: ble5-nrf52-mac   Author: tomasero   File: test_colors.py    MIT License 5 votes vote down vote up
def test_colormap_reversing(name):
    """Check the generated _lut data of a colormap and corresponding
    reversed colormap if they are almost the same."""
    cmap = plt.get_cmap(name)
    cmap_r = cmap.reversed()
    if not cmap_r._isinit:
        cmap._init()
        cmap_r._init()
    assert_array_almost_equal(cmap._lut[:-3], cmap_r._lut[-4::-1]) 
Example 43
Project: ble5-nrf52-mac   Author: tomasero   File: test_colorbar.py    MIT License 5 votes vote down vote up
def test_colorbar_single_scatter():
    # Issue #2642: if a path collection has only one entry,
    # the norm scaling within the colorbar must ensure a
    # finite range, otherwise a zero denominator will occur in _locate.
    plt.figure()
    x = np.arange(4)
    y = x.copy()
    z = np.ma.masked_greater(np.arange(50, 54), 50)
    cmap = plt.get_cmap('jet', 16)
    cs = plt.scatter(x, y, z, c=z, cmap=cmap)
    plt.colorbar(cs) 
Example 44
Project: mapper   Author: timothy-mcroy   File: MapperGUI.py    GNU General Public License v2.0 5 votes vote down vote up
def Colormap(Filter):
        # tbd: simplify
        import matplotlib.cm as mcm
        cmap = mcm.get_cmap()
        norm = mcm.colors.Normalize(vmin=Filter.min(), vmax=Filter.max())
        return mcm.ScalarMappable(norm=norm, cmap=cmap).to_rgba(Filter) 
Example 45
Project: 3d-vehicle-tracking   Author: ucbdrive   File: plot_utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, n, name='hsv'):
        '''Returns a function that maps each index in 0, 1, ..., n-1 to a 
        distinct 
        RGB color; the keyword argument name must be a standard mpl colormap 
        name.'''
        self.cmap = plt.cm.get_cmap(name, n)
        self.n = n 
Example 46
Project: Computable   Author: ktraunmueller   File: colorbar.py    MIT License 5 votes vote down vote up
def on_mappable_changed(self, mappable):
        """
        Updates this colorbar to match the mappable's properties.

        Typically this is automatically registered as an event handler
        by :func:`colorbar_factory` and should not be called manually.

        """
        self.set_cmap(mappable.get_cmap())
        self.set_clim(mappable.get_clim())
        self.update_normal(mappable) 
Example 47
Project: Computable   Author: ktraunmueller   File: plotting.py    MIT License 5 votes vote down vote up
def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
                         color=None):
    import matplotlib.pyplot as plt

    if color is None and colormap is not None:
        if isinstance(colormap, compat.string_types):
            import matplotlib.cm as cm
            cmap = colormap
            colormap = cm.get_cmap(colormap)
            if colormap is None:
                raise ValueError("Colormap {0} is not recognized".format(cmap))
        colors = lmap(colormap, np.linspace(0, 1, num=num_colors))
    elif color is not None:
        if colormap is not None:
            warnings.warn("'color' and 'colormap' cannot be used "
                          "simultaneously. Using 'color'")
        colors = color
    else:
        if color_type == 'default':
            colors = plt.rcParams.get('axes.color_cycle', list('bgrcmyk'))
            if isinstance(colors, compat.string_types):
                colors = list(colors)
        elif color_type == 'random':
            import random
            def random_color(column):
                random.seed(column)
                return [random.random() for _ in range(3)]

            colors = lmap(random_color, lrange(num_colors))
        else:
            raise NotImplementedError

    if len(colors) != num_colors:
        multiple = num_colors//len(colors) - 1
        mod = num_colors % len(colors)

        colors += multiple * colors
        colors += colors[:mod]

    return colors 
Example 48
Project: visualizing_momentum   Author: hengluchang   File: loss_surface.py    MIT License 5 votes vote down vote up
def plot(self):
        fig, ax = plt.subplots()
        cmap = cm.get_cmap('Greens_r')
        cp = ax.contour(self.X, self.Y, self.Z, 50, cmap=cmap)
        cbar = fig.colorbar(cp)
        cbar.set_label('loss')

        ax.set_xlim(-2.5, 2.5)
        ax.set_ylim(-0.5, 0.5)

        ax.set_xlabel('x')
        ax.set_ylabel('y')

        return fig, ax 
Example 49
Project: deep_lung_segmentation   Author: pedrocwb   File: seg_utils.py    MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output 
Example 50
Project: deep_lung_segmentation   Author: pedrocwb   File: seg_utils.py    MIT License 5 votes vote down vote up
def make_overlay(image, gt_prob):

    mycm = cm.get_cmap('bwr')

    overimage = mycm(gt_prob, bytes=True)
    output = 0.4*overimage[:,:,0:3] + 0.6*image

    return output