Python matplotlib.pylab.get_cmap() Examples

The following are 8 code examples of matplotlib.pylab.get_cmap(). 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.pylab , or try the search function .
Example #1
Source File: drawing.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #2
Source File: realtime_plotter.py    From visual_dynamics with MIT License 6 votes vote down vote up
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 
Example #3
Source File: drawing.py    From BIRL with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #4
Source File: plot_parameters_tried.py    From MDI with MIT License 5 votes vote down vote up
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) 
Example #5
Source File: plotting.py    From voxelmorph with GNU General Public License v3.0 4 votes vote down vote up
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) 
Example #6
Source File: vis.py    From learnable-triangulation-pytorch with MIT License 4 votes vote down vote up
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() 
Example #7
Source File: plot_parameters_tried.py    From MDI with MIT License 4 votes vote down vote up
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() 
Example #8
Source File: precipfields.py    From pysteps with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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