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


Python pylab.get_cmap方法代码示例

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


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

示例1: _list_colors

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def _list_colors(colors, nb):
    """ sample color space

    :param str|list colors:
    :param int nb:
    :return list:

    >>> _list_colors('jet', 2)
    [(0.0, 0.0, 0.5, 1.0), (0.5, 0.0, 0.0, 1.0)]
    >>> _list_colors(plt.cm.jet, 3)  # doctest: +ELLIPSIS
    [(0.0, 0.0, 0.5, 1.0), (0.0, 0.0, 0.5..., 1.0), (0.0, 0.0, 0.5..., 1.0)]
    >>> _list_colors([(255, 0, 0), (0, 255, 0)], 1)
    [(255, 0, 0), (0, 255, 0)]
    """
    # uf just color space is given, sample colors
    if isinstance(colors, str):
        colors = plt.get_cmap(colors, nb)
    # assume case that the color is callable plt.cm.jet
    if isinstance(colors, collections.Callable):
        colors = [colors(i) for i in range(nb)]
    return colors 
开发者ID:Borda,项目名称:BIRL,代码行数:23,代码来源:drawing.py

示例2: init

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def init(self, data_len):
        """
        Initialize plots based off the length of the data array.
        """
        self._t = 0
        self._data_len = data_len
        self._data = np.empty((0, data_len))

        cm = plt.get_cmap('spectral')
        self._plots = []
        for i in range(data_len):
            color = cm(1.0 * i / data_len)
            alpha = self._alphas[i] if self._alphas is not None else 1.0
            label = self._labels[i] if self._labels is not None else str(i)
            self._plots.append(
                self._ax.plot([], [], color=color, alpha=alpha, label=label)[0]
            )
        self._ax.set_xlim(0, self._time_window)
        self._ax.set_ylim(0, 1)
        self._ax.legend(loc='upper left', bbox_to_anchor=(0, 1.15))

        self._init = True 
开发者ID:alexlee-gk,项目名称:visual_dynamics,代码行数:24,代码来源:realtime_plotter.py

示例3: draw_matrix_user_ranking

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def draw_matrix_user_ranking(df_stat, higher_better=False, fig=None, cmap='tab20'):
    """ show matrix as image, sorted per column and unique colour per user

    :param DF df_stat: table where index are users and columns are scoring
    :param bool higher_better: ranking such that larger value is better
    :param fig: optional figure
    :param str cmap: color map
    :return Figure:

    >>> import pandas as pd
    >>> df = pd.DataFrame(np.random.random((5, 3)), columns=list('abc'))
    >>> draw_matrix_user_ranking(df)  # doctest: +ELLIPSIS
    <...>
    """
    ranking = compute_matrix_user_ranking(df_stat, higher_better)

    if fig is None:
        fig, _ = plt.subplots(figsize=np.array(df_stat.values.shape[::-1]) * 0.35)
    ax = fig.gca()
    arange = np.linspace(-0.5, len(df_stat) - 0.5, len(df_stat) + 1)
    norm = plt_colors.BoundaryNorm(arange, len(df_stat))
    fmt = plt_ticker.FuncFormatter(lambda x, pos: df_stat.index[x])

    draw_heatmap(ranking, np.arange(1, len(df_stat) + 1), df_stat.columns, ax=ax,
                 cmap=plt.get_cmap(cmap, len(df_stat)), norm=norm,
                 cbar_kw=dict(ticks=range(len(df_stat)), format=fmt),
                 cbar_label='Methods')
    ax.set_ylabel('Ranking')

    fig.tight_layout()
    return fig 
开发者ID:Borda,项目名称:BIRL,代码行数:33,代码来源:drawing.py

示例4: discrete_cmap

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def discrete_cmap(N, base_cmap=None):
    """Create an N-bin discrete colormap from the specified input map"""

    # Note that if base_cmap is a string or None, you can simply do
    #    return plt.cm.get_cmap(base_cmap, N)
    # The following works for string, None, or a colormap instance:

    base = plt.cm.get_cmap(base_cmap)
    color_list = base(np.linspace(0, 1, N))
    cmap_name = base.name + str(N)
    return base.from_list(cmap_name, color_list, N) 
开发者ID:rafaelvalle,项目名称:MDI,代码行数:13,代码来源:plot_parameters_tried.py

示例5: jitter

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def jitter(n=256, colmap="hsv", nargout=1):
    """
    jitter colormap of size [n x 3]. The jitter colormap will (likely) have distinct colors, with
    neighburing colors being quite different

    Parameters:
        n (optional): the size of the colormap. default:256
        colmap: the colormap to scramble. Either a string passable to plt.get_cmap,
            or a n-by-3 or n-by-4 array

    Algorithm: given a (preferably smooth) colormap as a starting point (default "hsv"), jitter
    reorders the colors by skipping roughly a quarter of the colors. So given jitter(9, "hsv"),
    jitter would take color numbers, in order, 1, 3, 5, 7, 9, 2, 4, 6, 8.

    Contact: adalca@csail.mit.edu
    """

    # get a 1:n vector
    idx = range(n)

    # roughly compute the quarter mark. in hsv, a quarter is enough to see a significant col change
    m = np.maximum(np.round(0.25 * n), 1).astype(int)

    # compute a new order, by reshaping this index array as a [m x ?] matrix, then vectorizing in
    # the opposite direction

    # pad with -1 to make it transformable to a square
    nb_elems = np.ceil(n / m) * m
    idx = np.pad(idx, [0, (nb_elems - n).astype(int)], 'constant', constant_values=-1)

    # permute elements by resizing to a matrix, transposing, and re-flatteneing
    idxnew = np.array(np.reshape(idx, [m, (nb_elems // m).astype(int)]).transpose().flatten())

    # throw away the extra elements
    idxnew = idxnew[np.where(idxnew >= 0)]
    assert len(idxnew) == n, "jitter: something went wrong with some inner logic :("

    # get colormap and scramble it
    if isinstance(colmap, six.string_types):
        cmap = plt.get_cmap(colmap, nb_elems)
        scrambled_cmap = cmap(idxnew)
    else:
        # assumes colmap is a nx3 or nx4
        assert colmap.shape[0] == n
        assert colmap.shape[1] == 3 or colmap.shape[1] == 4
        scrambled_cmap = colmap[idxnew, :]

    new_cmap = matplotlib.colors.ListedColormap(scrambled_cmap)
    if nargout == 1:
        return new_cmap
    else:
        assert nargout == 2
        return (new_cmap, scrambled_cmap) 
开发者ID:voxelmorph,项目名称:voxelmorph,代码行数:55,代码来源:plotting.py

示例6: draw_voxels

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def draw_voxels(voxels, ax, shape=(8, 8, 8), norm=True, alpha=0.1):
    # resize for visualization
    zoom = np.array(shape) / np.array(voxels.shape)
    voxels = skimage.transform.resize(voxels, shape, mode='constant', anti_aliasing=True)
    voxels = voxels.transpose(2, 0, 1)

    if norm and voxels.max() - voxels.min() > 0:
        voxels = (voxels - voxels.min()) / (voxels.max() - voxels.min())

    filled = np.ones(voxels.shape)

    # facecolors
    cmap = plt.get_cmap("Blues")

    facecolors_a = cmap(voxels, alpha=alpha)
    facecolors_a = facecolors_a.reshape(-1, 4)

    facecolors_hex = np.array(list(map(lambda x: matplotlib.colors.to_hex(x, keep_alpha=True), facecolors_a)))
    facecolors_hex = facecolors_hex.reshape(*voxels.shape)

    # explode voxels to perform 3d alpha rendering (https://matplotlib.org/devdocs/gallery/mplot3d/voxels_numpy_logo.html)
    def explode(data):
        size = np.array(data.shape) * 2
        data_e = np.zeros(size - 1, dtype=data.dtype)
        data_e[::2, ::2, ::2] = data
        return data_e

    filled_2 = explode(filled)
    facecolors_2 = explode(facecolors_hex)

    # shrink the gaps
    x, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2
    x[0::2, :, :] += 0.05
    y[:, 0::2, :] += 0.05
    z[:, :, 0::2] += 0.05
    x[1::2, :, :] += 0.95
    y[:, 1::2, :] += 0.95
    z[:, :, 1::2] += 0.95

    # draw voxels
    ax.voxels(x, y, z, filled_2, facecolors=facecolors_2)

    ax.set_xlabel("z"); ax.set_ylabel("x"); ax.set_zlabel("y")
    ax.invert_xaxis(); ax.invert_zaxis() 
开发者ID:karfly,项目名称:learnable-triangulation-pytorch,代码行数:46,代码来源:vis.py

示例7: plot_2d

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def plot_2d(params_dir):
    model_dirs = [name for name in os.listdir(params_dir)
                  if os.path.isdir(os.path.join(params_dir, name))]
    if len(model_dirs) == 0:
      model_dirs = [params_dir]


    colors = plt.get_cmap('plasma')
    plt.figure(figsize=(20, 10))
    ax = plt.subplot(111)
    ax.set_xlabel('Learning Rate')
    ax.set_ylabel('Error rate')

    i = 0
    for model_dir in model_dirs:
        model_df = pd.DataFrame()
        for param_path in glob.glob(os.path.join(params_dir,
                                                 model_dir) + '/*.h5'):
            param = dd.io.load(param_path)
            gd = {'learning rate': param['hyperparameters']['learning_rate'],
                  'momentum': param['hyperparameters']['momentum'],
                  'dropout': param['hyperparameters']['dropout'],
                  'val. objective': param['best_epoch']['validate_objective']}
            model_df = model_df.append(pd.DataFrame(gd, index=[0]),
                                       ignore_index=True)
        if i != len(model_dirs) - 1:
            ax.scatter(model_df['learning rate'],
                       model_df['val. objective'],
                       s=128,
                       marker=(i+3, 0),
                       edgecolor='black',
                       linewidth=model_df['dropout'],
                       label=model_dir,
                       c=model_df['momentum'],
                       cmap=colors)
        else:
            im = ax.scatter(model_df['learning rate'],
                            model_df['val. objective'],
                            s=128,
                            marker=(i+3, 0),
                            edgecolor='black',
                            linewidth=model_df['dropout'],
                            label=model_dir,
                            c=model_df['momentum'],
                            cmap=colors)
        i += 1

    plt.colorbar(im, label='Momentum')
    plt.legend()
    plt.show()
    plt.savefig('{}.eps'.format(os.path.join(IMAGES_DIRECTORY, 'params2d')), format='eps', dpi=1000)
    plt.close() 
开发者ID:rafaelvalle,项目名称:MDI,代码行数:54,代码来源:plot_parameters_tried.py

示例8: get_colormap

# 需要导入模块: from matplotlib import pylab [as 别名]
# 或者: from matplotlib.pylab import get_cmap [as 别名]
def get_colormap(type, units="mm/h", colorscale="pysteps"):
    """Function to generate a colormap (cmap) and norm.

    Parameters
    ----------
    type : {'intensity', 'depth', 'prob'}, optional
        Type of the map to plot: 'intensity' = precipitation intensity field,
        'depth' = precipitation depth (accumulation) field,
        'prob' = exceedance probability field.
    units : {'mm/h', 'mm', 'dBZ'}, optional
        Units of the input array. If type is 'prob', this specifies the unit of
        the intensity threshold.
    colorscale : {'pysteps', 'STEPS-BE', 'BOM-RF3'}, optional
        Which colorscale to use. Applicable if units is 'mm/h', 'mm' or 'dBZ'.

    Returns
    -------
    cmap : Colormap instance
        colormap
    norm : colors.Normalize object
        Colors norm
    clevs: list(float)
        List of precipitation values defining the color limits.
    clevsStr: list(str)
        List of precipitation values defining the color limits (with correct
        number of decimals).

    """
    if type in ["intensity", "depth"]:
        # Get list of colors
        color_list, clevs, clevsStr = _get_colorlist(units, colorscale)

        cmap = colors.LinearSegmentedColormap.from_list(
            "cmap", color_list, len(clevs) - 1
        )

        if colorscale == "BOM-RF3":
            cmap.set_over("black", 1)
        if colorscale == "pysteps":
            cmap.set_over("darkred", 1)
        if colorscale == "STEPS-BE":
            cmap.set_over("black", 1)
        norm = colors.BoundaryNorm(clevs, cmap.N)

        return cmap, norm, clevs, clevsStr

    elif type == "prob":
        cmap = plt.get_cmap("OrRd", 10)
        return cmap, colors.Normalize(vmin=0, vmax=1), None, None
    else:
        return cm.jet, colors.Normalize(), None, None 
开发者ID:pySTEPS,项目名称:pysteps,代码行数:53,代码来源:precipfields.py


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