Python matplotlib.pyplot.register_cmap() Examples

The following are 12 code examples of matplotlib.pyplot.register_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.pyplot , or try the search function .
Example #1
Source File: common.py    From typhon with MIT License 7 votes vote down vote up
def colors2cmap(*args, name=None):
    """Create a colormap from a list of given colors.

    Parameters:
        *args: Arbitrary number of colors (Named color, HEX or RGB).
        name (str): Name with which the colormap is registered.

    Returns:
        LinearSegmentedColormap.

    Examples:
        >>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
    """
    if len(args) < 2:
        raise Exception("Give at least two colors.")

    cmap_data = [_to_hex(c) for c in args]
    cmap = colors.LinearSegmentedColormap.from_list(name, cmap_data)
    plt.register_cmap(name, cmap)

    return cmap 
Example #2
Source File: test_colors.py    From typhon with MIT License 5 votes vote down vote up
def test_cmap_from_txt(self):
        """Import colormap from txt file."""
        viridis = plt.get_cmap('viridis')
        cmap = colors.cmap_from_txt(os.path.join(self.ref_dir, 'viridis.txt'))

        plt.register_cmap(cmap=viridis)  # Register original viridis.

        idx = np.linspace(0, 1, 256)
        assert np.allclose(viridis(idx), cmap(idx), atol=0.001) 
Example #3
Source File: test_colors.py    From typhon with MIT License 5 votes vote down vote up
def test_cmap_from_act(self):
        """Import colormap from act file."""
        viridis = plt.get_cmap('viridis')
        cmap = colors.cmap_from_act(os.path.join(self.ref_dir, 'viridis.act'))

        plt.register_cmap(cmap=viridis)  # Register original viridis.

        idx = np.linspace(0, 1, 256)
        assert np.allclose(viridis(idx), cmap(idx), atol=0.004) 
Example #4
Source File: common.py    From typhon with MIT License 5 votes vote down vote up
def cmap_from_act(file, name=None):
    """Import colormap from Adobe Color Table file.

    Parameters:
        file (str): Path to act file.
        name (str): Colormap name. Defaults to filename without extension.

    Returns:
        LinearSegmentedColormap.
    """
    # Extract colormap name from filename.
    if name is None:
        name = os.path.splitext(os.path.basename(file))[0]

    # Read binary file and determine number of colors
    rgb = np.fromfile(file, dtype=np.uint8)
    if rgb.shape[0] >= 770:
        ncolors = rgb[768] * 2**8 + rgb[769]
    else:
        ncolors = 256

    colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255

    # Create and register colormap...
    cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors)
    plt.register_cmap(cmap=cmap)  # Register colormap.

    # ... and the reversed colormap.
    cmap_r = LinearSegmentedColormap.from_list(
            name + '_r', np.flipud(colors), N=ncolors)
    plt.register_cmap(cmap=cmap_r)

    return cmap 
Example #5
Source File: common.py    From typhon with MIT License 5 votes vote down vote up
def cmap_from_txt(file, name=None, N=-1, comments='%'):
    """Import colormap from txt file.

    Reads colormap data (RGB/RGBA) from an ASCII file.
    Values have to be given in [0, 1] range.

    Parameters:
        file (str): Path to txt file.
        name (str): Colormap name. Defaults to filename without extension.
        N (int): Number of colors.
            ``-1`` means all colors (i.e., the complete file).
        comments (str): Character to start comments with.

    Returns:
        LinearSegmentedColormap.
    """
    # Extract colormap name from filename.
    if name is None:
        name = os.path.splitext(os.path.basename(file))[0]

    # Read binary file and determine number of colors
    rgb = np.genfromtxt(file, comments=comments)
    if N == -1:
        N = np.shape(rgb)[0]

    if np.min(rgb) < 0 or np.max(rgb) > 1:
        raise Exception('RGB value out of range: [0, 1].')

    # Create and register colormap...
    cmap = LinearSegmentedColormap.from_list(name, rgb, N=N)
    plt.register_cmap(cmap=cmap)

    # ... and the reversed colormap.
    cmap_r = LinearSegmentedColormap.from_list(
            name + '_r', np.flipud(rgb), N=N)
    plt.register_cmap(cmap=cmap_r)

    return cmap 
Example #6
Source File: LiCSBAS_plot_lib.py    From LiCSBAS with GNU General Public License v3.0 5 votes vote down vote up
def make_im_png(data, pngfile, cmap, title, vmin=None, vmax=None, cbar=True):
    """
    Make png image.
    cmap can be 'insar'. To wrap data, np.angle(np.exp(1j*x/cycle)*cycle)
    """

    if cmap=='insar':
        cdict = tools_lib.cmap_insar()
        plt.register_cmap(name='insar',data=cdict)
    
    length, width = data.shape
    figsizex = 8
    xmergin = 2 if cbar else 0
    figsizey = int((figsizex-xmergin)*(length/width))+1
    
    ### Plot
    fig, ax = plt.subplots(1, 1, figsize=(figsizex, figsizey))
    plt.tight_layout()
    
    im = ax.imshow(data, vmin=vmin, vmax=vmax, cmap=cmap)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_title(title)
    if cbar: fig.colorbar(im)

    plt.savefig(pngfile)
    plt.close()
    
    return


#%% 
Example #7
Source File: LiCSBAS_plot_lib.py    From LiCSBAS with GNU General Public License v3.0 5 votes vote down vote up
def make_3im_png(data3, pngfile, cmap, title3, vmin=None, vmax=None, cbar=True):
    """
    Make png with 3 images for comparison.
    data3 and title3 must be list with 3 elements.
    cmap can be 'insar'. To wrap data, np.angle(np.exp(1j*x/cycle)*cycle)
    """
    ### Plot setting
    if cmap=='insar':
        cdict = tools_lib.cmap_insar()
        plt.register_cmap(name='insar',data=cdict)

    length, width = data3[0].shape
    figsizex = 12
    xmergin = 4 if cbar else 0
    figsizey = int((figsizex-xmergin)/3*length/width)+2
    
    fig = plt.figure(figsize = (figsizex, figsizey))

    for i in range(3):
        ax = fig.add_subplot(1, 3, i+1) #index start from 1
        im = ax.imshow(data3[i], vmin=vmin, vmax=vmax, cmap=cmap)
        ax.set_title(title3[i])
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        if cbar: fig.colorbar(im, ax=ax)

    plt.tight_layout()
    plt.savefig(pngfile)
    plt.close()
   
    return 


#%% 
Example #8
Source File: plotting.py    From Pyspatialml with GNU General Public License v3.0 4 votes vote down vote up
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name="shiftedcmap"):
    """Function to offset the "center" of a colormap. Useful for data with a negative
    min and positive max and you want the middle of the colormap's dynamic range to be
    at zero.

    Source:
    http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib

    Parameters
    ----------
    cmap : str
        The matplotlib colormap to be altered

    start :  any number
        Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower
        offset). Should be between 0.0 and `midpoint`.
    midpoint :  any number between 0.0 and 1.0
        The new center of the colormap. Defaults to 0.5 (no shift). In general, this
        should be  1 - vmax/(vmax + abs(vmin)). For example if your data range from
        -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should
        be set to  1 - 5/(5 + 15)) or 0.75.
    stop :  any number between `midpoint` and 1.0
        Offset from highets point in the colormap's range. Defaults to 1.0 (no upper
        offset). 

    Returns
    -------
    matplotlib.cmap
        The colormap with its centre shifted to the midpoint value.
    """

    cdict = {"red": [], "green": [], "blue": [], "alpha": []}

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack(
        [
            np.linspace(0.0, midpoint, 128, endpoint=False),
            np.linspace(midpoint, 1.0, 129, endpoint=True),
        ]
    )

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict["red"].append((si, r, r))
        cdict["green"].append((si, g, g))
        cdict["blue"].append((si, b, b))
        cdict["alpha"].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap 
Example #9
Source File: GTExFigure.py    From Gene2vec with MIT License 4 votes vote down vote up
def shiftedColorMap(cmap, start=0.0, midpoint=0.75, stop=1.0, name='shiftedcmap'):
    '''
    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower ofset). Should be between
          0.0 and 1.0.
      midpoint : The new center of the colormap. Defaults to
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax/(vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          0.0 and 1.0.
    '''
    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False),
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = mcolors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap 
Example #10
Source File: utils.py    From time-domain-neural-audio-style-transfer with Apache License 2.0 4 votes vote down vote up
def rainbowgram(path,
                ax,
                peak=70.0,
                use_cqt=False,
                n_fft=1024,
                hop_length=256,
                sr=22050,
                over_sample=4,
                res_factor=0.8,
                octaves=5,
                notes_per_octave=10):
    audio = librosa.load(path, sr=sr)[0]
    if use_cqt:
        C = librosa.cqt(audio,
                        sr=sr,
                        hop_length=hop_length,
                        bins_per_octave=int(notes_per_octave * over_sample),
                        n_bins=int(octaves * notes_per_octave * over_sample),
                        filter_scale=res_factor,
                        fmin=librosa.note_to_hz('C2'))
    else:
        C = librosa.stft(
            audio,
            n_fft=n_fft,
            win_length=n_fft,
            hop_length=hop_length,
            center=True)
    mag, phase = librosa.core.magphase(C)
    phase_angle = np.angle(phase)
    phase_unwrapped = np.unwrap(phase_angle)
    dphase = phase_unwrapped[:, 1:] - phase_unwrapped[:, :-1]
    dphase = np.concatenate([phase_unwrapped[:, 0:1], dphase], axis=1) / np.pi
    mag = (librosa.logamplitude(
        mag**2, amin=1e-13, top_db=peak, ref_power=np.max) / peak) + 1
    cdict = {
        'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'alpha': ((0.0, 1.0, 1.0), (1.0, 0.0, 0.0))
    }
    my_mask = matplotlib.colors.LinearSegmentedColormap('MyMask', cdict)
    plt.register_cmap(cmap=my_mask)
    ax.matshow(dphase[::-1, :], cmap=plt.cm.rainbow)
    ax.matshow(mag[::-1, :], cmap=my_mask) 
Example #11
Source File: figtools.py    From CoolBox with GNU General Public License v3.0 4 votes vote down vote up
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    This function is from: https://stackoverflow.com/a/20528097/8500469

    Function to offset the "center" of a colormap. Useful for
    data with a negative min and positive max and you want the
    middle of the colormap's dynamic range to be at zero

    Input
    -----
      cmap : The matplotlib colormap to be altered
      start : Offset from lowest point in the colormap's range.
          Defaults to 0.0 (no lower ofset). Should be between
          0.0 and `midpoint`.
      midpoint : The new center of the colormap. Defaults to
          0.5 (no shift). Should be between 0.0 and 1.0. In
          general, this should be  1 - vmax/(vmax + abs(vmin))
          For example if your data range from -15.0 to +5.0 and
          you want the center of the colormap at 0.0, `midpoint`
          should be set to  1 - 5/(5 + 15)) or 0.75
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          `midpoint` and 1.0.

    '''
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt

    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)

    # shifted index to match the data
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False),
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])

    for ri, si in zip(reg_index, shift_index):
        r, g, b, a = cmap(ri)

        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))

    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap 
Example #12
Source File: LiCSBAS_loop_lib.py    From LiCSBAS with GNU General Public License v3.0 4 votes vote down vote up
def make_loop_png(ifgd12, ifgd23, ifgd13, unw12, unw23, unw13, loop_ph, loop_pngdir):
    ### Load color map for InSAR
    cdict = tools_lib.cmap_insar()
    plt.register_cmap(name='insar', data=cdict)

    rms = np.sqrt(np.nanmean(loop_ph**2))

    ### Settings    
    imd1 = ifgd12[:8]
    imd2 = ifgd23[:8]
    imd3 = ifgd23[-8:]
    pngname = os.path.join(loop_pngdir, imd1+'_'+imd2+'_'+imd3+'_loop.png')
    cycle = 3 # 2pi*3/cycle
    titles = [ifgd12, ifgd23, ifgd13]
    data = [unw12, unw23, unw13]

    length, width = unw12.shape
    if length > width:
        figsize_y = 10
        figsize_x = int((figsize_y-1)*width/length)
        if figsize_x < 5: figsize_x = 5
    else:
        figsize_x = 10
        figsize_y = int(figsize_x*length/width+1)
        if figsize_y < 3: figsize_y = 3
                
    ### Plot
    fig = plt.figure(figsize = (figsize_x, figsize_y))

    ## 3 ifgs
    for i in range(3):
        data_wrapped = np.angle(np.exp(1j*(data[i]/cycle))*cycle)
        ax = fig.add_subplot(2, 2, i+1) #index start from 1
        ax.imshow(data_wrapped, vmin=-np.pi, vmax=+np.pi, cmap='insar')
        ax.set_title('{}'.format(titles[i]))
        ax.set_xticklabels([])
        ax.set_yticklabels([])

    ## loop phase
    ax = fig.add_subplot(2, 2, 4) #index start from 1
    ax.imshow(loop_ph, vmin=-np.pi, vmax=+np.pi, cmap=SCM.vik)
    ax.set_title('Loop phase (RMS={:.2f}rad)'.format(rms))
    ax.set_xticklabels([])
    ax.set_yticklabels([])

    plt.tight_layout()
    plt.savefig(pngname)
    plt.close()