当前位置: 首页>>代码示例>>Python>>正文


Python colors.Colormap方法代码示例

本文整理汇总了Python中matplotlib.colors.Colormap方法的典型用法代码示例。如果您正苦于以下问题:Python colors.Colormap方法的具体用法?Python colors.Colormap怎么用?Python colors.Colormap使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.colors的用法示例。


在下文中一共展示了colors.Colormap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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)) 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:21,代码来源:colours.py

示例2: slice3d

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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) 
开发者ID:neuro-ml,项目名称:deep_pipe,代码行数:25,代码来源:visualize.py

示例3: test_get_cmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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') 
开发者ID:dcs4cop,项目名称:xcube,代码行数:19,代码来源:test_cmaps.py

示例4: get_cmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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 ) 
开发者ID:MNGuenther,项目名称:allesfitter,代码行数:20,代码来源:colormaputil.py

示例5: get_ctab

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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)]) 
开发者ID:liamedeiros,项目名称:ehtplot,代码行数:6,代码来源:ctab.py

示例6: truncate_colormap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:32,代码来源:colours.py

示例7: discrete_colourmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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) 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:30,代码来源:colours.py

示例8: colorbar_index

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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 
开发者ID:LSDtopotools,项目名称:LSDMappingTools,代码行数:40,代码来源:colours.py

示例9: register_cmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:39,代码来源:cm.py

示例10: get_cmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:30,代码来源:cm.py

示例11: __init__

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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} 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:30,代码来源:cm.py

示例12: dpt_timeseries

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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) 
开发者ID:theislab,项目名称:scanpy,代码行数:41,代码来源:__init__.py

示例13: dpt_groups_pseudotime

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
def dpt_groups_pseudotime(
    adata: AnnData,
    color_map: Union[str, Colormap, None] = None,
    palette: Union[Sequence[str], Cycler, None] = None,
    show: Optional[bool] = None,
    save: Union[bool, str, None] = None,
):
    """Plot groups and pseudotime."""
    _, (ax_grp, ax_ord) = pl.subplots(2, 1)
    timeseries_subplot(
        adata.obs['dpt_groups'].cat.codes,
        time=adata.obs['dpt_order'].values,
        color=np.asarray(adata.obs['dpt_groups']),
        highlights_x=adata.uns['dpt_changepoints'],
        ylabel='dpt groups',
        yticks=(
            np.arange(len(adata.obs['dpt_groups'].cat.categories), dtype=int)
            if len(adata.obs['dpt_groups'].cat.categories) < 5
            else None
        ),
        palette=palette,
        ax=ax_grp,
    )
    timeseries_subplot(
        adata.obs['dpt_pseudotime'].values,
        time=adata.obs['dpt_order'].values,
        color=adata.obs['dpt_pseudotime'].values,
        xlabel='dpt order',
        highlights_x=adata.uns['dpt_changepoints'],
        ylabel='pseudotime',
        yticks=[0, 1],
        color_map=color_map,
        ax=ax_ord,
    )
    savefig_or_show('dpt_groups_pseudotime', save=save, show=show) 
开发者ID:theislab,项目名称:scanpy,代码行数:37,代码来源:__init__.py

示例14: _slice_base

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
def _slice_base(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,
                callback: Callable = None, sliders: dict = None):
    from ipywidgets import interact, IntSlider
    check_shape_along_axis(*data, axis=axis)
    vlim = np.broadcast_to(vlim, [len(data), 2]).tolist()
    rows, columns = _get_rows_cols(max_columns, data)
    sliders = sliders or {}
    if 'idx' in sliders:
        raise ValueError(f'Overriding "idx" is not allowed.')

    def update(idx, **kwargs):
        fig, axes = plt.subplots(rows, columns, figsize=(scale * columns, scale * rows))
        for ax, x, (vmin, vmax) in zip(np.array(axes).flatten(), data, vlim):
            im = ax.imshow(x.take(idx, axis=axis), cmap=cmap, vmin=vmin, vmax=vmax)
            if colorbar:
                fig.colorbar(im, ax=ax, orientation='horizontal')
            if not show_axes:
                ax.set_axis_off()

        if callback is not None:
            callback(axes, idx=idx, **kwargs)

        plt.tight_layout()
        plt.show()

    interact(update, idx=IntSlider(min=0, max=data[0].shape[axis] - 1, continuous_update=False), **sliders) 
开发者ID:neuro-ml,项目名称:deep_pipe,代码行数:29,代码来源:visualize.py

示例15: get_cmap

# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import Colormap [as 别名]
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)
    else:
        raise ValueError(
            "Colormap %s is not recognized. Possible values are: %s"
            % (name, ', '.join(cmap_d.keys()))) 
开发者ID:miloharper,项目名称:neural-network-animation,代码行数:32,代码来源:cm.py


注:本文中的matplotlib.colors.Colormap方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。