Python matplotlib.colors.Colormap() Examples

The following are 30 code examples of matplotlib.colors.Colormap(). 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 , or try the search function .
Example #1
Source File: test_cmaps.py    From xcube with MIT License 6 votes vote down vote up
def test_get_cmap(self):
        ensure_cmaps_loaded()

        cmap_name, cmap = get_cmap('plasma')
        self.assertEqual('plasma', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        cmap_name, cmap = get_cmap('PLASMA')
        self.assertEqual('viridis', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        cmap_name, cmap = get_cmap('PLASMA', default_cmap_name='magma')
        self.assertEqual('magma', cmap_name)
        self.assertIsInstance(cmap, Colormap)

        with self.assertRaises(ValueError):
            get_cmap('PLASMA', default_cmap_name='MAGMA') 
Example #2
Source File: colours.py    From LSDMappingTools with 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 #3
Source File: visualize.py    From deep_pipe with MIT License 6 votes vote down vote up
def slice3d(*data: np.ndarray, axis: int = -1, scale: int = 5, max_columns: int = None, colorbar: bool = False,
            show_axes: bool = False, cmap: Union[Colormap, str] = 'gray', vlim: AxesParams = None):
    """
    Creates an interactive plot, simultaneously showing slices along a given ``axis`` for all the passed images.

    Parameters
    ----------
    data
    axis
    scale
        the figure scale.
    max_columns
        the maximal number of figures in a row. If None - all figures will be in the same row.
    colorbar
        Whether to display a colorbar.
    show_axes
        Whether to do display grid on the image.
    cmap
    vlim
        used to normalize luminance data. If None - the limits are determined automatically.
        Must be broadcastable to (len(data), 2). See `matplotlib.pyplot.imshow` (vmin and vmax) for details.
    """
    _slice_base(data, axis, scale, max_columns, colorbar, show_axes, cmap, vlim) 
Example #4
Source File: colormaputil.py    From allesfitter with MIT License 6 votes vote down vote up
def get_cmap( cmap, name=None, n=256 ):
    """ in: a name "Blues" "BuGn_r" ... of a builtin cmap (case-sensitive)
        or a filename, np.loadtxt() n x 3 or 4  ints 0..255 or floats 0..1
        or a cmap already
        or a numpy array.
        See http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
        or in IPython, pl.cm.<tab>
    """
    if isinstance( cmap, colors.Colormap ):
        return cmap
    if isinstance( cmap, str ):
        if cmap in cm.cmap_d:
            return pl.get_cmap( cmap )  # "Blues" ...
        A = np.loadtxt( cmap, delimiter=None )  # None: white space
        name = name or cmap.split("/")[-1] .split(".")[0]  # .../xx.csv -> xx
    else:
        A = cmap  # numpy array or array-like
    return array_cmap( A, name, n=n ) 
Example #5
Source File: cm.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a standard
    mpl colormap name.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        else:
            return cmap_d[name]._resample(lut)
    else:
        raise ValueError(
            "Colormap %s is not recognized. Possible values are: %s"
            % (name, ', '.join(sorted(cmap_d)))) 
Example #6
Source File: cm.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not isinstance(name, str):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #7
Source File: cm.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a standard
    mpl colormap name.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        else:
            return cmap_d[name]._resample(lut)
    else:
        raise ValueError(
            "Colormap %s is not recognized. Possible values are: %s"
            % (name, ', '.join(sorted(cmap_d)))) 
Example #8
Source File: cm.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
            If *None*, *norm* defaults to a *colors.Normalize* object which
            initializes its scaling based on the first data processed.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.
        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #9
Source File: util.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mplcmap_to_palette(cmap, ncolors=None, categorical=False):
    """
    Converts a matplotlib colormap to palette of RGB hex strings."
    """
    from matplotlib.colors import Colormap, ListedColormap

    ncolors = ncolors or 256
    if not isinstance(cmap, Colormap):
        import matplotlib.cm as cm
        # Alias bokeh Category cmaps with mpl tab cmaps
        if cmap.startswith('Category'):
            cmap = cmap.replace('Category', 'tab')
        try:
            cmap = cm.get_cmap(cmap)
        except:
            cmap = cm.get_cmap(cmap.lower())
    if isinstance(cmap, ListedColormap):
        if categorical:
            palette = [rgb2hex(cmap.colors[i%cmap.N]) for i in range(ncolors)]
            return palette
        elif cmap.N > ncolors:
            palette = [rgb2hex(c) for c in cmap(np.arange(cmap.N))]
            if len(palette) != ncolors:
                palette = [palette[int(v)] for v in np.linspace(0, len(palette)-1, ncolors)]
            return palette
    return [rgb2hex(c) for c in cmap(np.linspace(0, 1, ncolors))] 
Example #10
Source File: colormaputil.py    From allesfitter with MIT License 5 votes vote down vote up
def array_cmap( A, name=None, n=256 ):
    """ numpy array -> a cmap, matplotlib.colors.Colormap
        n x 3 or 4  ints 0 .. 255 or floats 0 ..1
    """
    A = np.asanyarray( A )
    assert A.ndim == 2  and A.shape[1] in (3, 4), \
            "array must be n x 3 or 4, not %s" % str(A.shape)
    Amin, Amax = A.min(), A.max()
    if A.dtype.kind == "i":
        assert 0 <= Amin < Amax <= 255, "Amin %d  Amax %d must be in 0 .. 255" % (Amin, Amax)
        A = A / 255.  # not /=
    else:
        assert 0 <= Amin < Amax <= 1, "Amin %g  Amax %g must be in 0 .. 1" % (Amin, Amax)
    return colors.LinearSegmentedColormap.from_list( name or "noname", A, N=n ) 
Example #11
Source File: cm.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not isinstance(name, str):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #12
Source File: cm.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
            If *None*, *norm* defaults to a *colors.Normalize* object which
            initializes its scaling based on the first data processed.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.
        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #13
Source File: cm.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
            If *None*, *norm* defaults to a *colors.Normalize* object which
            initializes its scaling based on the first data processed.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.
        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #14
Source File: cm.py    From CogAlg with MIT License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not isinstance(name, str):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #15
Source File: cm.py    From CogAlg with MIT License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a standard
    mpl colormap name.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        else:
            return cmap_d[name]._resample(lut)
    else:
        raise ValueError(
            "Colormap %s is not recognized. Possible values are: %s"
            % (name, ', '.join(sorted(cmap_d)))) 
Example #16
Source File: cm.py    From CogAlg with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
            If *None*, *norm* defaults to a *colors.Normalize* object which
            initializes its scaling based on the first data processed.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.
        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #17
Source File: test_utils.py    From msmexplorer with MIT License 5 votes vote down vote up
def test_make_colormap():
    cmap = make_colormap(['rawdenim', 'lightgray', 'pomegranate'])
    assert isinstance(cmap, Colormap) 
Example #18
Source File: cm.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not isinstance(name, six.string_types):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #19
Source File: cm.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a standard
    mpl colormap name.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        else:
            return cmap_d[name]._resample(lut)
    else:
        raise ValueError(
            "Colormap %s is not recognized. Possible values are: %s"
            % (name, ', '.join(sorted(cmap_d)))) 
Example #20
Source File: cm.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
            If *None*, *norm* defaults to a *colors.Normalize* object which
            initializes its scaling based on the first data processed.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.
        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #21
Source File: __init__.py    From scanpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dpt_timeseries(
    adata: AnnData,
    color_map: Union[str, Colormap] = None,
    show: Optional[bool] = None,
    save: Optional[bool] = None,
    as_heatmap: bool = True,
):
    """\
    Heatmap of pseudotime series.

    Parameters
    ----------
    as_heatmap
        Plot the timeseries as heatmap.
    """
    if adata.n_vars > 100:
        logg.warning(
            'Plotting more than 100 genes might take some while, '
            'consider selecting only highly variable genes, for example.'
        )
    # only if number of genes is not too high
    if as_heatmap:
        # plot time series as heatmap, as in Haghverdi et al. (2016), Fig. 1d
        timeseries_as_heatmap(
            adata.X[adata.obs['dpt_order_indices'].values],
            var_names=adata.var_names,
            highlights_x=adata.uns['dpt_changepoints'],
            color_map=color_map,
        )
    else:
        # plot time series as gene expression vs time
        timeseries(
            adata.X[adata.obs['dpt_order_indices'].values],
            var_names=adata.var_names,
            highlights_x=adata.uns['dpt_changepoints'],
            xlim=[0, 1.3 * adata.X.shape[0]],
        )
    pl.xlabel('dpt order')
    savefig_or_show('dpt_timeseries', save=save, show=show) 
Example #22
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 #23
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 #24
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def colorbar_index(fig, cax, ncolors, cmap, drape_min_threshold, drape_max):
    """State-machine like function that creates a discrete colormap and plots
       it on a figure that is passed as an argument.

    Arguments:
       fig (matplotlib.Figure): Instance of a matplotlib figure object.
       cax (matplotlib.Axes): Axes instance to create the colourbar from.
           This must be the Axes containing the data that your colourbar will be
           mapped from.
       ncolors (int): The number of colours in the discrete colourbar map.
       cmap (str or Colormap object): Either the name of a matplotlib colormap, or
           an object instance of the colormap, e.g. cm.jet
       drape_min_threshold (float): Number setting the threshold level of the drape raster
           This should match any threshold you have set to mask the drape/overlay raster.
       drape_max (float): Similar to above, but for the upper threshold of your drape mask.
    """

    discrete_cmap = discrete_colourmap(ncolors, cmap)

    mappable = _cm.ScalarMappable(cmap=discrete_cmap)
    mappable.set_array([])
    #mappable.set_clim(-0.5, ncolors + 0.5)
    mappable.set_clim(drape_min_threshold, drape_max)

    print(type(fig))
    print(type(mappable))
    print(type(cax))
    print()
    cbar = _plt.colorbar(mappable, cax=cax) #switched from fig to plt to expose the labeling params
    print(type(cbar))
    #cbar.set_ticks(_np.linspace(0, ncolors, ncolors))
    pad = ((ncolors - 1) / ncolors) / 2  # Move labels to center of bars.
    cbar.set_ticks(_np.linspace(drape_min_threshold + pad, drape_max - pad,
                   ncolors))

    return cbar

# Generate random colormap 
Example #25
Source File: cm.py    From Computable with MIT License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not cbook.is_string_like(name):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #26
Source File: cm.py    From Computable with MIT License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a
    standard mpl colormap name with a corresponding data dictionary
    in *datad*.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        elif name in datad:
            return _generate_cmap(name, lut)

    raise ValueError("Colormap %s is not recognized" % name) 
Example #27
Source File: cm.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.

        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False} 
Example #28
Source File: cm.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def register_cmap(name=None, cmap=None, data=None, lut=None):
    """
    Add a colormap to the set recognized by :func:`get_cmap`.

    It can be used in two ways::

        register_cmap(name='swirly', cmap=swirly_cmap)

        register_cmap(name='choppy', data=choppydata, lut=128)

    In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
    instance.  The *name* is optional; if absent, the name will
    be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

    In the second case, the three arguments are passed to
    the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
    and the resulting colormap is registered.

    """
    if name is None:
        try:
            name = cmap.name
        except AttributeError:
            raise ValueError("Arguments must include a name or a Colormap")

    if not cbook.is_string_like(name):
        raise ValueError("Colormap name must be a string")

    if isinstance(cmap, colors.Colormap):
        cmap_d[name] = cmap
        return

    # For the remainder, let exceptions propagate.
    if lut is None:
        lut = mpl.rcParams['image.lut']
    cmap = colors.LinearSegmentedColormap(name, data, lut)
    cmap_d[name] = cmap 
Example #29
Source File: cm.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def get_cmap(name=None, lut=None):
    """
    Get a colormap instance, defaulting to rc values if *name* is None.

    Colormaps added with :func:`register_cmap` take precedence over
    built-in colormaps.

    If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
    returned.

    If *lut* is not None it must be an integer giving the number of
    entries desired in the lookup table, and *name* must be a
    standard mpl colormap name with a corresponding data dictionary
    in *datad*.
    """
    if name is None:
        name = mpl.rcParams['image.cmap']

    if isinstance(name, colors.Colormap):
        return name

    if name in cmap_d:
        if lut is None:
            return cmap_d[name]
        elif name in datad:
            return _generate_cmap(name, lut)

    raise ValueError("Colormap %s is not recognized" % name) 
Example #30
Source File: cm.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __init__(self, norm=None, cmap=None):
        r"""

        Parameters
        ----------
        norm : :class:`matplotlib.colors.Normalize` instance
            The normalizing object which scales data, typically into the
            interval ``[0, 1]``.
        cmap : str or :class:`~matplotlib.colors.Colormap` instance
            The colormap used to map normalized data values to RGBA colors.

        """

        self.callbacksSM = cbook.CallbackRegistry()

        if cmap is None:
            cmap = get_cmap()
        if norm is None:
            norm = colors.Normalize()

        self._A = None
        #: The Normalization instance of this ScalarMappable.
        self.norm = norm
        #: The Colormap instance of this ScalarMappable.
        self.cmap = get_cmap(cmap)
        #: The last colorbar associated with this ScalarMappable. May be None.
        self.colorbar = None
        self.update_dict = {'array': False}