Python matplotlib.colors.ListedColormap() Examples

The following are 30 code examples of matplotlib.colors.ListedColormap(). 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: plot_helpers.py    From cate with MIT License 6 votes vote down vote up
def _color_palette(cmap, n_colors):
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap
    import numpy as np

    colors_i = np.linspace(0, 1., n_colors)
    if isinstance(cmap, (list, tuple)):
        # we have a list of colors
        cmap = ListedColormap(cmap, N=n_colors)
        pal = cmap(colors_i)
    elif isinstance(cmap, str):
        # we have some sort of named palette
        try:
            # is this a matplotlib cmap?
            ensure_cmaps_loaded()
            cmap = plt.get_cmap(cmap)
        except ValueError:
            # or maybe we just got a single color as a string
            cmap = ListedColormap([cmap], N=n_colors)
        pal = cmap(colors_i)
    else:
        # cmap better be a LinearSegmentedColormap (e.g. viridis)
        pal = cmap(colors_i)

    return pal 
Example #2
Source File: test_colors.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_resample():
    """
    Github issue #6025 pointed to incorrect ListedColormap._resample;
    here we test the method for LinearSegmentedColormap as well.
    """
    n = 101
    colorlist = np.empty((n, 4), float)
    colorlist[:, 0] = np.linspace(0, 1, n)
    colorlist[:, 1] = 0.2
    colorlist[:, 2] = np.linspace(1, 0, n)
    colorlist[:, 3] = 0.7
    lsc = mcolors.LinearSegmentedColormap.from_list('lsc', colorlist)
    lc = mcolors.ListedColormap(colorlist)
    lsc3 = lsc._resample(3)
    lc3 = lc._resample(3)
    expected = np.array([[0.0, 0.2, 1.0, 0.7],
                         [0.5, 0.2, 0.5, 0.7],
                         [1.0, 0.2, 0.0, 0.7]], float)
    assert_array_almost_equal(lsc3([0, 0.5, 1]), expected)
    assert_array_almost_equal(lc3([0, 0.5, 1]), expected) 
Example #3
Source File: colormaps.py    From qiskit-ibmq-provider with Apache License 2.0 6 votes vote down vote up
def _sns_to_plotly(cmap: ListedColormap, pl_entries: int = 255
                   ) -> List[List[Union[float, str]]]:
    """Convert a color map to a plotly color scale.

    Args:
        cmap: Color map to be converted.
        pl_entries: Number of entries in the color scale.

    Returns:
        Color scale.
    """
    hgt = 1.0/(pl_entries-1)
    pl_colorscale = []

    for k in range(pl_entries):
        clr = list(map(np.uint8, np.array(cmap(k*hgt)[:3])*255))
        pl_colorscale.append([k*hgt, 'rgb'+str((clr[0], clr[1], clr[2]))])

    return pl_colorscale 
Example #4
Source File: main.py    From youtube with GNU General Public License v3.0 6 votes vote down vote up
def plot_slic(array, clusters, K, S, output_figure = ''):
    fig = plt.figure(figsize=(8, 6))
    # create colormap based on cluster RGB centers
    slic_colormap = []
    for c in clusters:
        slic_colormap.append((c[0], c[1], c[2], 1.0))
    slic_listed_colormap = ListedColormap(slic_colormap)
    slic_norm = BoundaryNorm(range(K), K)
    plt.imshow(array, norm=slic_norm, cmap=slic_listed_colormap)
    # adjust image
    (rows, columns) = array.shape
    plt.xlim([0 - S, columns + S])
    plt.ylim([0 - S, rows + S])

    if output_figure != '':
        plt.savefig(output_figure, format='png', dpi=1000)
    else:
        plt.show()

# open dataset 
Example #5
Source File: display.py    From pycpt with GNU General Public License v2.0 6 votes vote down vote up
def plot_colormap(cmap, continuous=True, discrete=True, ndisc=9):
    """Make a figure displaying the color map in continuous and/or discrete form
    """
    nplots = int(continuous) + int(discrete)
    fig, axx = plt.subplots(figsize=(6,.5*nplots), nrows=nplots, frameon=False)
    axx = np.asarray(axx)
    i=0
    if continuous:
        norm = mcolors.Normalize(vmin=0, vmax=1)
        ColorbarBase(axx.flat[i], cmap=cmap, norm=norm, orientation='horizontal') ; i+=1
    if discrete:
        colors = cmap(np.linspace(0, 1, ndisc))
        cmap_d = mcolors.ListedColormap(colors, name=cmap.name)
        norm = mcolors.BoundaryNorm(np.linspace(0, 1, ndisc+1), len(colors))
        ColorbarBase(axx.flat[i], cmap=cmap_d, norm=norm, orientation='horizontal')
    for ax in axx.flat:
        ax.set_axis_off()
    fig.text(0.95, 0.5, cmap.name, va='center', ha='left', fontsize=12) 
Example #6
Source File: load.py    From pycpt with GNU General Public License v2.0 6 votes vote down vote up
def cmap_from_geo_uoregon(cname,
        baseurl='http://geog.uoregon.edu/datagraphics/color/',
        download=False):
    """Parse an online file from geography.uoregon.edu to create a Python colormap"""
    ext = '.txt'

    url = urljoin(baseurl, cname+ext)
    print(url)
    
    # process file directly from online source
    req = Request(url)
    response = urlopen(req)
    rgb = np.loadtxt(response, skiprows=2)
    
    # save original file
    if download:
        fname = os.path.basename(url) + ext
        urlretrieve (url, fname)
        
    return mcolors.ListedColormap(rgb, cname) 
Example #7
Source File: RDMcolormap.py    From pyrsa with GNU Lesser General Public License v3.0 6 votes vote down vote up
def RDMcolormap(nCols=256):

    # blue-cyan-gray-red-yellow with increasing V (BCGRYincV)
    anchorCols = np.array([
        [0, 0, 1],
        [0, 1, 1],
        [.5, .5, .5],
        [1, 0, 0],
        [1, 1, 0],
    ])

    # skimage rgb2hsv is intended for 3d images (RGB)
    # here we add a new axis to our 2d anchorCols to satisfy skimage, and then squeeze
    anchorCols_hsv = rgb2hsv(anchorCols[np.newaxis, :]).squeeze()

    incVweight = 1
    anchorCols_hsv[:, 2] = (1-incVweight)*anchorCols_hsv[:, 2] + \
        incVweight*np.linspace(0.5, 1, anchorCols.shape[0]).T

    # anchorCols = brightness(anchorCols)
    anchorCols = hsv2rgb(anchorCols_hsv[np.newaxis, :]).squeeze()

    cols = colorScale(nCols, anchorCols)

    return ListedColormap(cols) 
Example #8
Source File: instance_attention.py    From Scale-Adaptive-Network with MIT License 6 votes vote down vote up
def show(self, image, label_1s, label_2s, label_3s, label, label_at):
        import matplotlib.pyplot as plt
        from matplotlib import colors
        # make a color map of fixed colors
        cmap = colors.ListedColormap([(0,0,0), (0.5,0,0), (0,0.5,0), (0.5,0.5,0), (0,0,0.5), (0.5,0,0.5), (0,0.5,0.5)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)

        fig, axes = plt.subplots(2,3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        ax1.set_title('image'); ax1.imshow(image)
        ax3.set_title('label'); ax2.imshow(label, cmap=cmap, norm=norm)
        ax3.set_title('label 1s'); ax3.imshow(label_1s, cmap=cmap, norm=norm)
        ax4.set_title('label 2s'); ax4.imshow(label_2s, cmap=cmap, norm=norm)
        ax5.set_title('label 3s'); ax5.imshow(label_3s, cmap=cmap, norm=norm)
        ax6.set_title('label at'); ax6.imshow(label_at, cmap=cmap, norm=norm)
        plt.show() 
Example #9
Source File: figure4_5_no_sklearn.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_decision(features, labels):
    '''Plots decision boundary for KNN

    Parameters
    ----------
    features : ndarray
    labels : sequence

    Returns
    -------
    fig : Matplotlib Figure
    ax  : Matplotlib Axes
    '''
    y0, y1 = features[:, 2].min() * .9, features[:, 2].max() * 1.1
    x0, x1 = features[:, 0].min() * .9, features[:, 0].max() * 1.1
    X = np.linspace(x0, x1, 100)
    Y = np.linspace(y0, y1, 100)
    X, Y = np.meshgrid(X, Y)

    model = fit_model(1, features[:, (0, 2)], np.array(labels))
    C = predict(
        np.vstack([X.ravel(), Y.ravel()]).T, model).reshape(X.shape)
    if COLOUR_FIGURE:
        cmap = ListedColormap([(1., .6, .6), (.6, 1., .6), (.6, .6, 1.)])
    else:
        cmap = ListedColormap([(1., 1., 1.), (.2, .2, .2), (.6, .6, .6)])
    fig,ax = plt.subplots()
    ax.set_xlim(x0, x1)
    ax.set_ylim(y0, y1)
    ax.set_xlabel(feature_names[0])
    ax.set_ylabel(feature_names[2])
    ax.pcolormesh(X, Y, C, cmap=cmap)
    if COLOUR_FIGURE:
        cmap = ListedColormap([(1., .0, .0), (.0, 1., .0), (.0, .0, 1.)])
        ax.scatter(features[:, 0], features[:, 2], c=labels, cmap=cmap)
    else:
        for lab, ma in zip(range(3), "Do^"):
            ax.plot(features[labels == lab, 0], features[
                     labels == lab, 2], ma, c=(1., 1., 1.))
    return fig,ax 
Example #10
Source File: part_attention.py    From Scale-Adaptive-Network with MIT License 6 votes vote down vote up
def show(self, image, label_1s, label_2s, label_3s, label, label_at):
        import matplotlib.pyplot as plt
        from matplotlib import colors
        # make a color map of fixed colors
        cmap = colors.ListedColormap([(0,0,0), (0.5,0,0), (0,0.5,0), (0.5,0.5,0), (0,0,0.5), (0.5,0,0.5), (0,0.5,0.5)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)

        fig, axes = plt.subplots(2,3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        ax1.set_title('image'); ax1.imshow(image)
        ax3.set_title('label'); ax2.imshow(label, cmap=cmap, norm=norm)
        ax3.set_title('label 1s'); ax3.imshow(label_1s, cmap=cmap, norm=norm)
        ax4.set_title('label 2s'); ax4.imshow(label_2s, cmap=cmap, norm=norm)
        ax5.set_title('label 3s'); ax5.imshow(label_3s, cmap=cmap, norm=norm)
        ax6.set_title('label at'); ax6.imshow(label_at, cmap=cmap, norm=norm)
        plt.show() 
Example #11
Source File: plot_boundary_on_data.py    From try-tf with Apache License 2.0 6 votes vote down vote up
def plot(X,Y,pred_func):
    # determine canvas borders
    mins = np.amin(X,0); 
    mins = mins - 0.1*np.abs(mins);
    maxs = np.amax(X,0); 
    maxs = maxs + 0.1*maxs;

    ## generate dense grid
    xs,ys = np.meshgrid(np.linspace(mins[0,0],maxs[0,0],300), 
            np.linspace(mins[0,1], maxs[0,1], 300));


    # evaluate model on the dense grid
    Z = pred_func(np.c_[xs.flatten(), ys.flatten()]);
    Z = Z.reshape(xs.shape)

    # Plot the contour and training examples
    plt.contourf(xs, ys, Z, cmap=plt.cm.Spectral)
    plt.scatter(X[:, 0], X[:, 1], c=Y[:,1], s=50,
            cmap=colors.ListedColormap(['orange', 'blue']))
    plt.show() 
Example #12
Source File: example7.py    From bert-as-service with MIT License 6 votes vote down vote up
def vis(embed, vis_alg='PCA', pool_alg='REDUCE_MEAN'):
    plt.close()
    fig = plt.figure()
    plt.rcParams['figure.figsize'] = [21, 7]
    for idx, ebd in enumerate(embed):
        ax = plt.subplot(2, 6, idx + 1)
        vis_x = ebd[:, 0]
        vis_y = ebd[:, 1]
        plt.scatter(vis_x, vis_y, c=subset_label, cmap=ListedColormap(["blue", "green", "yellow", "red"]), marker='.',
                    alpha=0.7, s=2)
        ax.set_title('pool_layer=-%d' % (idx + 1))
    plt.tight_layout()
    plt.subplots_adjust(bottom=0.1, right=0.95, top=0.9)
    cax = plt.axes([0.96, 0.1, 0.01, 0.3])
    cbar = plt.colorbar(cax=cax, ticks=range(num_label))
    cbar.ax.get_yaxis().set_ticks([])
    for j, lab in enumerate(['ent.', 'bus.', 'sci.', 'heal.']):
        cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center', rotation=270)
    fig.suptitle('%s visualization of BERT layers using "bert-as-service" (-pool_strategy=%s)' % (vis_alg, pool_alg),
                 fontsize=14)
    plt.show() 
Example #13
Source File: sf_heatmap.py    From pancanatlas_code_public with MIT License 6 votes vote down vote up
def _override_sns_row_colors(graph, row_colors):

    if not isinstance(row_colors, list):
        row_colors = row_colors.tolist()
    if isinstance(row_colors[0], tuple):
        # row_colors are in rgb(a) form
        unq_colors, color_class = np.unique(row_colors, axis=0, return_inverse=True)
        unq_colors = map(lambda x: tuple(x), unq_colors)
    else:
        unq_colors, color_class = np.unique(row_colors, return_inverse=True)
        unq_colors = unq_colors.tolist()

    rcax = graph.ax_row_colors
    rcax.clear()
    cmap = colors.ListedColormap(unq_colors)
    rcax.imshow(np.matrix(color_class).T, aspect='auto', cmap=cmap)
    rcax.get_xaxis().set_visible(False)
    rcax.get_yaxis().set_visible(False)

    return 
Example #14
Source File: test_colors.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_resample():
    """
    Github issue #6025 pointed to incorrect ListedColormap._resample;
    here we test the method for LinearSegmentedColormap as well.
    """
    n = 101
    colorlist = np.empty((n, 4), float)
    colorlist[:, 0] = np.linspace(0, 1, n)
    colorlist[:, 1] = 0.2
    colorlist[:, 2] = np.linspace(1, 0, n)
    colorlist[:, 3] = 0.7
    lsc = mcolors.LinearSegmentedColormap.from_list('lsc', colorlist)
    lc = mcolors.ListedColormap(colorlist)
    lsc3 = lsc._resample(3)
    lc3 = lc._resample(3)
    expected = np.array([[0.0, 0.2, 1.0, 0.7],
                         [0.5, 0.2, 0.5, 0.7],
                         [1.0, 0.2, 0.0, 0.7]], float)
    assert_array_almost_equal(lsc3([0, 0.5, 1]), expected)
    assert_array_almost_equal(lc3([0, 0.5, 1]), expected) 
Example #15
Source File: nifti_viewer.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def check_segmentation(fn_subject):
    from scipy import ndimage
    import matplotlib.pylab as pl
    from matplotlib.colors import ListedColormap
    files = simnibs.SubjectFiles(fn_subject + '.msh')
    T1 = nib.load(files.T1)
    masks = nib.load(files.final_contr).get_data()
    lines = np.linalg.norm(np.gradient(masks), axis=0) > 0
    print(lines.shape)
    viewer = NiftiViewer(T1.get_data(), T1.affine)
    cmap = pl.cm.jet
    my_cmap = cmap(np.arange(cmap.N))
    my_cmap[:,-1] = np.linspace(0, 1, cmap.N)
    my_cmap = ListedColormap(my_cmap)
    viewer.add_overlay(lines, cmap=my_cmap)
    viewer.show() 
Example #16
Source File: cmap.py    From ehtplot with GNU General Public License v3.0 6 votes vote down vote up
def ehtcmap(N=Nq,
            Jpmin=15.0, Jpmax=95.0,
            Cpmin= 0.0, Cpmax=64.0,
            hpmin=None, hpmax=90.0,
            hp=None,
            **kwargs):
    name = kwargs.pop('name', "new eht colormap")

    Jp = np.linspace(Jpmin, Jpmax, num=N)
    if hp is None:
        if hpmin is None:
            hpmin = hpmax - 60.0
        q  = 0.25 * (hpmax - hpmin)
        hp = np.clip(np.linspace(hpmin-3*q, hpmax+q, num=N), hpmin, hpmax)
    elif callable(hp):
        hp = hp(np.linspace(0.0, 1.0, num=N))
    hp *= np.pi/180.0
    Cp = max_chroma(Jp, hp, Cpmin=Cpmin, Cpmax=Cpmax)

    Jpapbp = np.stack([Jp, Cp * np.cos(hp), Cp * np.sin(hp)], axis=-1)
    Jpapbp = symmetrize(Jpapbp, **kwargs)
    sRGB   = transform(Jpapbp, inverse=True)
    return ListedColormap(np.clip(sRGB, 0, 1), name=name) 
Example #17
Source File: get_attention_of_branches.py    From Scale-Adaptive-Network with MIT License 5 votes vote down vote up
def handle_three_branches(self, im, result, final, op_1s, op_2s, op_3s):
        fig, axes = plt.subplots(2, 3)
        (ax1, ax2, ax3), (ax4, ax5, ax6) = axes
        fig.set_size_inches(16, 8, forward=True)

        ax1.set_title('im')
        ax1.imshow(im)

        # make a color map of fixed colors
        cmap = colors.ListedColormap([(0,0,0), (0.5,0,0), (0,0.5,0), (0.5,0.5,0), (0,0,0.5), (0.5,0,0.5), (0,0.5,0.5)])
        bounds=[0,1,2,3,4,5,6,7]
        norm = colors.BoundaryNorm(bounds, cmap.N)
        ax2.set_title('prediction')
        ax2.imshow(result, cmap=cmap, norm=norm)

        ax3.set_title('branch_1s')
        im1 = ax3.imshow(op_1s)
        divider3 = make_axes_locatable(ax3)
        cax3 = divider3.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im1, cax=cax3)

        ax4.set_title('branch_2s')
        im2 = ax4.imshow(op_2s)
        divider4 = make_axes_locatable(ax4)
        cax4 = divider4.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im2, cax=cax4)

        ax5.set_title('branch_3s')
        im3 = ax5.imshow(op_3s)
        divider5 = make_axes_locatable(ax5)
        cax5 = divider5.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(im3, cax=cax5)

        ax6.set_title('final output')
        fl = ax6.imshow(final, vmin=0, vmax=1)
        divider6 = make_axes_locatable(ax6)
        cax6 = divider6.append_axes("right", size="5%", pad=0.05)
        plt.colorbar(fl, cax=cax6)

        #plt.show()
        return fig 
Example #18
Source File: utils.py    From SC-SfMLearner-Release with GNU General Public License v3.0 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 #19
Source File: engine.py    From Clairvoyant with MIT License 5 votes vote down vote up
def visualize(self, name, width=5, height=5, stepsize=0.02):
        if len(self.features) != 2:
            print("Error: Plotting is restricted to 2 dimensions")
            return
        if self.model == None:
            print("Error: Please start model before visualizing")
            return
            
        X, y = self.model.XX, self.model.yy # Retrieve previous XX and yy                                      
        X = self.model.scaler.transform(X)  # Normalize X values
        self.model.svc.fit(X, y)            # Refit model
        
        x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5    
        y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5     
        xx, yy = meshgrid(arange(x_min, x_max, stepsize), arange(y_min, y_max, stepsize))
        
        pyplot.figure(figsize=(width, height))
        cm = pyplot.cm.RdBu  # Red/Blue gradients
        rb = ListedColormap(['#FF312E', '#6E8894']) # Red = 0 (Negative) / Blue = 1 (Positve)
        Z = self.model.svc.decision_function(c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        
        Axes = pyplot.subplot(1,1,1)
        Axes.set_title(name)
        Axes.contourf(xx, yy, Z, cmap=cm, alpha=0.75)
        Axes.scatter(X[:, 0], X[:, 1], s=20, c=y, cmap=rb, edgecolors='black') 
        Axes.set_xlim(xx.min(), xx.max())
        Axes.set_ylim(yy.min(), yy.max())
        pyplot.savefig("{0}.png".format(name)) 
Example #20
Source File: human_parse.py    From Scale-Adaptive-Network with MIT License 5 votes vote down vote up
def show_result(gt):
    import matplotlib.pyplot as plt
    from matplotlib import colors
    fig, axes = plt.subplots(1, 1)
    ax1 = axes
    fig.set_size_inches(10, 8, forward=True)

    # make a color map of fixed colors
    cmap = colors.ListedColormap([(0,0,0), (0.5,0,0), (0,0.5,0), (0.5,0.5,0), (0,0,0.5), (0.5,0,0.5), (0,0.5,0.5)])
    bounds=[0,1,2,3,4,5,6,7]
    norm = colors.BoundaryNorm(bounds, cmap.N)
    ax1.set_title('gt')
    ax1.imshow(gt, cmap=cmap, norm=norm)
    plt.show() 
Example #21
Source File: qc.py    From spinalcordtoolbox with MIT License 5 votes vote down vote up
def label_vertebrae(self, mask, ax):
        """Draw vertebrae areas, then add text showing the vertebrae names"""
        from matplotlib import colors
        import scipy.ndimage
        img = np.rint(np.ma.masked_where(mask < 1, mask))
        ax.imshow(img,
                  cmap=colors.ListedColormap(self._labels_color),
                  norm=colors.Normalize(vmin=0, vmax=len(self._labels_color)),
                  interpolation=self.interpolation,
                  alpha=1,
                  aspect=float(self.aspect_mask))
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        a = [0.0]
        data = mask
        for index, val in np.ndenumerate(data):
            if val not in a:
                a.append(val)
                index = int(val)
                if index in self._labels_regions.values():
                    color = self._labels_color[index]
                    y, x = scipy.ndimage.measurements.center_of_mass(np.where(data == val, data, 0))
                    # Draw text with a shadow
                    x += 10
                    label = list(self._labels_regions.keys())[list(self._labels_regions.values()).index(index)]
                    ax.text(x, y, label, color='black', clip_on=True)
                    x -= 0.5
                    y -= 0.5
                    ax.text(x, y, label, color=color, clip_on=True) 
Example #22
Source File: ColorMap.py    From trappy with Apache License 2.0 5 votes vote down vote up
def rgb_cmap(cls, rgb_list):
        """Constructor for a ColorMap from an rgb_list

        :param rgb_list: A list of rgb tuples for red, green and blue.
            The rgb values should be in the range 0-255.
        :type rgb_list: list of tuples
        """

        rgb_list = [[x / 255.0 for x in rgb[:3]] for rgb in rgb_list]

        rgb_map = ListedColormap(rgb_list, name='default_color_map', N=None)
        num_colors = len(rgb_list)

        return cls(num_colors, cmap=rgb_map) 
Example #23
Source File: util.py    From DLWP with MIT License 5 votes vote down vote up
def radar_colormap():
    """
    Function to output a matplotlib color map object for reflectivity based on
    the National Weather Service color scheme.
    """

    nws_reflectivity_colors = [
        #    "#646464", # ND
        #    "#ccffff", # -30
        #    "#cc99cc", # -25
        #    "#996699", # -20
        #    "#663366", # -15
        #    "#cccc99", # -10
        #    "#999966", # -5
        #    "#646464", # 0
        "#ffffff",  # 0 white
        "#04e9e7",  # 5
        "#019ff4",  # 10
        "#0300f4",  # 15
        "#02fd02",  # 20
        "#01c501",  # 25
        "#008e00",  # 30
        "#fdf802",  # 35
        "#e5bc00",  # 40
        "#fd9500",  # 45
        "#fd0000",  # 50
        "#d40000",  # 55
        "#bc0000",  # 60
        "#f800fd",  # 65
        "#9854c6",  # 70
        #    "#fdfdfd" # 75
    ]
    return ListedColormap(nws_reflectivity_colors) 
Example #24
Source File: plot.py    From starfish with MIT License 5 votes vote down vote up
def _linear_alpha_cmap(cmap):
    """add linear alpha to an existing colormap"""
    alpha_cmap = cmap(np.arange(cmap.N))
    alpha_cmap[:, -1] = np.linspace(0, 1, cmap.N)
    return ListedColormap(alpha_cmap) 
Example #25
Source File: data_class.py    From MIDI-VAE with MIT License 5 votes vote down vote up
def draw_difference_pianoroll(original, predicted, name_1='Original', name_2='Predicted', show=False, save_path=''):

    if original.shape!=predicted.shape:
        print("Shape mismatch. Not drawing a plot.")
        return

    draw_matrix = original + 2 * predicted
    
    cm = colors.ListedColormap(['white', 'blue', 'red', 'black'])
    bounds=[0,1,2,3,4]
    n = colors.BoundaryNorm(bounds, cm.N)

    original_color = cm(1/3)
    predicted_color = cm(2/3)
    both_color = cm(1.0)

    original_patch = mpatches.Patch(color=original_color, label=name_1)
    predicted_patch = mpatches.Patch(color=predicted_color, label=name_2)
    both_patch = mpatches.Patch(color=both_color, label='Notes in both songs')

    plt.figure(figsize=(20.0, 10.0))
    plt.title('Difference-Pitch-plot of ' + name_1 + ' and ' + name_2, fontsize=10)
    plt.legend(handles=[original_patch, predicted_patch, both_patch], loc='upper right', prop={'size': 8})

    plt.pcolor(draw_matrix, cmap=cm, vmin=0, vmax=3, norm=n)
    if show:
        plt.show()
    if len(save_path) > 0:
        plt.savefig(save_path)
        tikz_save(save_path + ".tex", encoding='utf-8', show_info=False)
        
    plt.close() 
Example #26
Source File: utils.py    From scvelo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rgb_custom_colormap(colors=None, alpha=None, N=256):
    """Creates a custom colormap. Colors can be given as names or rgb values.

    Arguments
    ---------
    colors: : `list` or `array` (default `['royalblue', 'white', 'forestgreen']`)
        List of colors, either as names or rgb values.
    alpha: `list`, `np.ndarray` or `None` (default: `None`)
        Alpha of the colors. Must be same length as colors.
    N: `int` (default: `256`)
        y coordinate

    Returns
    -------
        A ListedColormap
    """
    if colors is None:
        colors = ["royalblue", "white", "forestgreen"]
    c = []
    if "transparent" in colors:
        if alpha is None:
            alpha = [1 if i != "transparent" else 0 for i in colors]
        colors = [i if i != "transparent" else "white" for i in colors]

    for color in colors:
        if isinstance(color, str):
            color = to_rgb(color if color.startswith("#") else cnames[color])
            c.append(color)
    if alpha is None:
        alpha = np.ones(len(c))

    vals = np.ones((N, 4))
    ints = len(c) - 1
    n = int(N / ints)

    for j in range(ints):
        for i in range(3):
            vals[n * j : n * (j + 1), i] = np.linspace(c[j][i], c[j + 1][i], n)
        vals[n * j : n * (j + 1), -1] = np.linspace(alpha[j], alpha[j + 1], n)
    return ListedColormap(vals) 
Example #27
Source File: utilities.py    From safe_learning with MIT License 5 votes vote down vote up
def binary_cmap(color='red', alpha=1.):
    """Construct a binary colormap."""
    if color == 'red':
        color_code = (1., 0., 0., alpha)
    elif color == 'green':
        color_code = (0., 1., 0., alpha)
    elif color == 'blue':
        color_code = (0., 0., 1., alpha)
    else:
        color_code = color
    transparent_code = (1., 1., 1., 0.)
    return ListedColormap([transparent_code, color_code]) 
Example #28
Source File: palettes.py    From scvelo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plot_color_cylce(clists: Mapping[str, Sequence[str]]):
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.colors import ListedColormap, BoundaryNorm

    fig, axes = plt.subplots(nrows=len(clists))  # type: plt.Figure, plt.Axes
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.3, right=0.99)
    axes[0].set_title("Color Maps/Cycles", fontsize=14)

    for ax, (name, clist) in zip(axes, clists.items()):
        n = len(clist)
        ax.imshow(
            np.arange(n)[None, :].repeat(2, 0),
            aspect="auto",
            cmap=ListedColormap(clist),
            norm=BoundaryNorm(np.arange(n + 1) - 0.5, n),
        )
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, name, va="center", ha="right", fontsize=10)

    # Turn off all ticks & spines
    for ax in axes:
        ax.set_axis_off()
    fig.show() 
Example #29
Source File: colors.py    From pyvista with MIT License 5 votes vote down vote up
def get_cmap_safe(cmap):
    """Fetch a colormap by name from matplotlib, colorcet, or cmocean."""
    try:
        from matplotlib.cm import get_cmap
    except ImportError:
        raise ImportError('cmap requires matplotlib')
    if isinstance(cmap, str):
        # Try colorcet first
        try:
            import colorcet
            cmap = colorcet.cm[cmap]
        except (ImportError, KeyError):
            pass
        else:
            return cmap
        # Try cmocean second
        try:
            import cmocean
            cmap = getattr(cmocean.cm, cmap)
        except (ImportError, AttributeError):
            pass
        else:
            return cmap
        # Else use Matplotlib
        cmap = get_cmap(cmap)
    elif isinstance(cmap, list):
        for item in cmap:
            if not isinstance(item, str):
                raise TypeError('When inputting a list as a cmap, each item should be a string.')
        from matplotlib.colors import ListedColormap
        cmap = ListedColormap(cmap)

    return cmap 
Example #30
Source File: utils.py    From nxviz with MIT License 5 votes vote down vote up
def n_group_colorpallet(n):
    """If more then 8 categorical groups of nodes or edges this function
    creats the matching color_palette
    """
    cmap = ListedColormap(sns.color_palette("hls", n))
    return cmap