Python matplotlib.colors.LinearSegmentedColormap() Examples

The following are 30 code examples of matplotlib.colors.LinearSegmentedColormap(). 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: colours.py    From LSDMappingTools with MIT License 6 votes vote down vote up
def cmap_discretize(N, cmap):
    """Return a discrete colormap from the continuous colormap cmap.

    Arguments:
        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example:
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = _plt.get_cmap(cmap)
    colors_i = _np.concatenate((_np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = _np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                       for i in range(N+1) ]
    # Return colormap object.
    return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024) 
Example #2
Source File: helper.py    From bayesloop with MIT License 6 votes vote down vote up
def createColormap(color, min_factor=1.0, max_factor=0.95):
    """
    Creates colormap with range 0-1 from white to arbitrary color.

    Args:
        color: Matplotlib-readable color representation. Examples: 'g', '#00FFFF', '0.5', [0.1, 0.5, 0.9]
        min_factor(float): Float in the range 0-1, specifying the gray-scale color of the minimal plot value.
        max_factor(float): Float in the range 0-1, multiplication factor of 'color' argument for maximal plot value.

    Returns:
        Colormap object to be used by matplotlib-functions
    """
    rgb = colors.colorConverter.to_rgb(color)
    cdict = {'red':   [(0.0, min_factor, min_factor),
                       (1.0, max_factor*rgb[0], max_factor*rgb[0])],

             'green': [(0.0, min_factor, min_factor),
                       (1.0, max_factor*rgb[1], max_factor*rgb[1])],

             'blue':  [(0.0, min_factor, min_factor),
                       (1.0, max_factor*rgb[2], max_factor*rgb[2])]}

    return colors.LinearSegmentedColormap('custom', cdict) 
Example #3
Source File: gpf.py    From PyCINRAD with GNU General Public License v3.0 6 votes vote down vote up
def gpf(self):
        cmap = {"red": [], "green": [], "blue": []}
        with open(self.filepath, "r") as f:
            lastred = (0.0, 0.0, 0.0)
            lastgreen = lastred
            lastblue = lastred
            line = f.readline()
            while line:
                if line[0] != "#":
                    data = [ast.literal_eval(numbyte) for numbyte in line.split()]
                    red = (data[0], lastred[2], data[1])
                    green = (data[0], lastgreen[2], data[2])
                    blue = (data[0], lastblue[2], data[3])
                    cmap["red"].append(red)
                    cmap["green"].append(green)
                    cmap["blue"].append(blue)
                    lastred = red
                    lastgreen = green
                    lastblue = blue
                line = f.readline()
        return dict(cmap=mclr.LinearSegmentedColormap("gpf", cmap)) 
Example #4
Source File: plotting.py    From recurrent-slds with MIT License 6 votes vote down vote up
def gradient_cmap(gcolors, nsteps=256, bounds=None):
    """
    Make a colormap that interpolates between a set of colors
    """
    ncolors = len(gcolors)
    if bounds is None:
        bounds = np.linspace(0, 1, ncolors)

    reds = []
    greens = []
    blues = []
    alphas = []
    for b, c in zip(bounds, gcolors):
        reds.append((b, c[0], c[0]))
        greens.append((b, c[1], c[1]))
        blues.append((b, c[2], c[2]))
        alphas.append((b, c[3], c[3]) if len(c) == 4 else (b, 1., 1.))

    cdict = {'red': tuple(reds),
             'green': tuple(greens),
             'blue': tuple(blues),
             'alpha': tuple(alphas)}

    cmap = LinearSegmentedColormap('grad_colormap', cdict, nsteps)
    return cmap 
Example #5
Source File: predcel_plot.py    From AiGEM_TeamHeidelberg2017 with MIT License 6 votes vote down vote up
def plot_dist_f(v, o, prefix, suffix, summariesdir):
    xkeys = range(len(v.dist_f))
    ykeys = list(v.dist_f[0].keys())
    f_share = np.ndarray([len(ykeys), len(xkeys)])


    for x in range(f_share.shape[1]):
        for y in range(f_share.shape[0]):
                f_share[y, x] = v.dist_f[xkeys[x]][ykeys[y]]
    ccmap = mplcolors.LinearSegmentedColormap('by_cmap', cdict2)
    fig, ax = plt.subplots(dpi=300)

    pcm = ax.imshow(f_share, origin='lower',
                    extent=[v.time[0], v.time[-1], ykeys[0], ykeys[-1]],
                    aspect='auto',
                    cmap=ccmap)
    clb = fig.colorbar(pcm, ax=ax)

    clb.set_label('share of given share of M13 wt fitness', y=0.5)
    plt.title('Development of fitness distribution')
    plt.ylabel('Fitness relative to wt M13 fitness')
    plt.xlabel('Time [min]')

    plt.savefig(os.path.join(summariesdir, "{}fitness_distribution_{}.png".format(prefix, suffix)))
    plt.close() 
Example #6
Source File: meanderpy.py    From meanderpy with Apache License 2.0 6 votes vote down vote up
def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    [from: https://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale]
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict) 
Example #7
Source File: colormap.py    From Ocean-Data-Map-Project with GNU General Public License v3.0 6 votes vote down vote up
def make_colormap(seq):
    """
    Return a LinearSegmentedColormap: http://stackoverflow.com/a/16836182
    Args:
        seq: a sequence of floats and RGB-tuples. The floats should be increasing
        and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict) 
Example #8
Source File: cm_colorblind.py    From pycwr with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from it's name *name*. The lut size is
    *lutsize*."""

    spec = datad[name]
    # Generate the colormap object.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", FutureWarning)
        if 'red' in spec:
            return colors.LinearSegmentedColormap(name, spec, lutsize)
        else:
            return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #9
Source File: cm.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
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 isinstance(name, six.string_types):
        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 
Example #10
Source File: cm.py    From pycwr with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from it's name *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #11
Source File: colorbar.py    From marvin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _string_to_cmap(cm_name):
    """Return colormap given name.

    Parameters:
        cm_name (str):
            Name of colormap.

    Returns:
        `matplotlib.cm <http://matplotlib.org/api/cm_api.html>`_ (colormap)
        object
    """
    if isinstance(cm_name, str):
        if 'linearlab' in cm_name:
            try:
                cmap, cmap_r = linearlab()
            except IOError:
                cmap = cm.viridis
            else:
                if '_r' in cm_name:
                    cmap = cmap_r
        else:
            cmap = cm.get_cmap(cm_name)
    elif isinstance(cm_name, ListedColormap) or isinstance(cm_name, LinearSegmentedColormap):
        cmap = cm_name
    else:
        raise MarvinError('{} is not a valid cmap'.format(cm_name))

    return cmap 
Example #12
Source File: diverging_map.py    From kepler_orrery with MIT License 5 votes vote down vote up
def diverge_map(RGB1=np.array([59, 76, 192]), RGB2=np.array([180, 4, 38]),
                numColors=101):
    # create a new instance of the ColorMapCreator-class using the desired
    # options
    colormap = ColorMapCreator(RGB1, RGB2, numColors=numColors)
    # there's clearly some bugs since it's possible to get values > 1
    # e.g. with starting values RGB1 = [1,185,252], RGB2 = [220, 55, 19],
    # numColors > 3
    # but this is good enough for now
    colormap.colorMap = np.clip(colormap.colorMap, 0, 1)

    cdict = {'red': [], 'green': [], 'blue': []}
    inds = np.linspace(0.,1.,numColors)

    # create a matplotlib colormap
    for ii, ind in enumerate(inds):
        cdict['red'].append([ind, colormap.colorMap[ii, 0],
                             colormap.colorMap[ii, 0]])
        cdict['green'].append([ind, colormap.colorMap[ii, 1],
                               colormap.colorMap[ii, 1]])
        cdict['blue'].append([ind, colormap.colorMap[ii, 2],
                              colormap.colorMap[ii, 2]])

    from matplotlib.colors import LinearSegmentedColormap
    mycmap = LinearSegmentedColormap('BlueRed1', cdict)

    return mycmap 
Example #13
Source File: vawt.py    From pyGeoPressure with MIT License 5 votes vote down vote up
def opendtect_seismic_colormap():
    normalizer = Normalize(vmin=0, vmax=255)

    cdict = {
        'red': [
            (0, float(normalizer(170)), float(normalizer(170))),
            (0.070352, float(normalizer(255)), float(normalizer(255))),
            (0.25, float(normalizer(255)), float(normalizer(255))),
            (0.5, float(normalizer(243)), float(normalizer(243))),
            (0.88324, float(normalizer(56)), float(normalizer(56))),
            (1.0, 0.0, 0.0)
        ],
        'green': [
            (0.0, 0.0, 0.0),
            (0.070352, float(normalizer(28)), float(normalizer(28))),
            (0.25, float(normalizer(200)), float(normalizer(200))),
            (0.5, float(normalizer(243)), float(normalizer(243))),
            (0.88324, float(normalizer(70)), float(normalizer(70))),
            (1.0, 0.0, 0.0)
        ],
        'blue': [
            (0.0, 0.0, 0.0),
            (0.070352, 0, 0),
            (0.25, 0, 0),
            (0.5, float(normalizer(243)), float(normalizer(243))),
            (0.88324, float(normalizer(127)), float(normalizer(127))),
            (1.0, 0.0, 0.0)
        ]
    }

    return LinearSegmentedColormap('Seismic_OD', cdict) 
Example #14
Source File: cm.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from its *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    elif 'listed' in spec:
        return colors.ListedColormap(spec['listed'], name)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #15
Source File: cm.py    From coffeegrindsize with MIT License 5 votes vote down vote up
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 isinstance(name, str):
        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 
Example #16
Source File: cm.py    From CogAlg with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from its *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    elif 'listed' in spec:
        return colors.ListedColormap(spec['listed'], name)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #17
Source File: cm.py    From CogAlg with MIT License 5 votes vote down vote up
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 isinstance(name, str):
        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 
Example #18
Source File: colors.py    From landlab with MIT License 5 votes vote down vote up
def water_colormap():
    """Return matplotlib colormap with 'water' theme."""
    cdict = {
        "red": ((0.0, 0.0, 169.0 / 255.0), (1.0, 38.0 / 255.0, 1.0)),
        "green": ((0.0, 0.0, 222.0 / 255.0), (1.0, 39.0 / 255.0, 1.0)),
        "blue": ((0.0, 0.0, 242.0 / 255.0), (1.0, 23.0 / 255.0, 1.0)),
    }
    return LinearSegmentedColormap("landlab_water", cdict) 
Example #19
Source File: colors.py    From landlab with MIT License 5 votes vote down vote up
def earth_colormap():
    """Return matplotlib colormap with 'earth' theme."""
    cdict = {
        "red": ((0.0, 0.0, 252.0 / 255.0), (1.0, 33.0 / 255.0, 1.0)),
        "green": ((0.0, 0.0, 237.0 / 255.0), (1.0, 38.0 / 255.0, 1.0)),
        "blue": ((0.0, 0.0, 179.0 / 255.0), (1.0, 24.0 / 255.0, 1.0)),
    }
    return LinearSegmentedColormap("landlab_earth", cdict) 
Example #20
Source File: colors.py    From tropycal with MIT License 5 votes vote down vote up
def make_colormap(colors,whiten=0):
    
    z  = np.array(sorted(colors.keys()))
    n  = len(z)
    z1 = min(z)
    zn = max(z)
    x0 = (z - z1) / (zn - z1)
    
    CC = mcolors.ColorConverter()
    R = []
    G = []
    B = []
    for i in range(n):
        Ci = colors[z[i]]
        if type(Ci) == str:
            RGB = CC.to_rgb(Ci)
        else:
            RGB = Ci
        R.append(RGB[0] + (1-RGB[0])*whiten)
        G.append(RGB[1] + (1-RGB[1])*whiten)
        B.append(RGB[2] + (1-RGB[2])*whiten)
    
    cmap_dict = {}
    cmap_dict['red']   = [(x0[i],R[i],R[i]) for i in range(len(R))]
    cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
    cmap_dict['blue']  = [(x0[i],B[i],B[i]) for i in range(len(B))]
    mymap = mcolors.LinearSegmentedColormap('mymap',cmap_dict)
    
    return mymap 
Example #21
Source File: ctables.py    From lmatools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_cmap(name, lut=None):
    if lut is None: lut = LUTSIZE
    
    #If lut is < 0, then return the table with only levels originally defined
    if lut < 0:
        lut = len(datad[name]['red'])
    return colors.LinearSegmentedColormap(name,  datad[name], lut)

#Taken from the matplotlib cookbook 
Example #22
Source File: ctables.py    From lmatools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def cmap_map(function,cmap):
    """ Applies function (which should operate on vectors of shape 3:
    [r, g, b], on colormap cmap. This routine will break any discontinuous
    points in a colormap.
    
    Example usage:
    light_jet = cmap_map(lambda x: x/2+0.5, cm.jet)
    """
    cdict = cmap._segmentdata
    step_dict = {}
    # First get the list of points where the segments start or end
    for key in ('red','green','blue'):
        step_dict[key] = map(lambda x: x[0], cdict[key])
    step_list = reduce(lambda x, y: x+y, step_dict.values())
    step_list = array(list(set(step_list)))
    # Then compute the LUT, and apply the function to the LUT
    reduced_cmap = lambda step : array(cmap(step)[0:3])
    old_LUT = array(map( reduced_cmap, step_list))
    new_LUT = array(map( function, old_LUT))
    # Now try to make a minimal segment definition of the new LUT
    cdict = {}
    for i,key in enumerate(('red','green','blue')):
        this_cdict = {}
        for j,step in enumerate(step_list):
            if step in step_dict[key]:
                this_cdict[step] = new_LUT[j,i]
            elif new_LUT[j,i]!=old_LUT[j,i]:
                this_cdict[step] = new_LUT[j,i]
        colorvector=  map(lambda x: x + (x[1], ), this_cdict.items())
        colorvector.sort()
        cdict[key] = colorvector

    return colors.LinearSegmentedColormap('colormap',cdict,1024) 
Example #23
Source File: cm.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from its *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    elif 'listed' in spec:
        return colors.ListedColormap(spec['listed'], name)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #24
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
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 
Example #25
Source File: test_load.py    From pycpt with GNU General Public License v2.0 5 votes vote down vote up
def test_cmap_from_cptcity_url(self):
        cmap = cmap_from_cptcity_url('ngdc/ETOPO1.cpt')
        self.assertIsInstance(cmap, mcolors.LinearSegmentedColormap) 
Example #26
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def __call__(self, function, cmap):
        return _mcolors.LinearSegmentedColormap('colormap', self.cdict, 1024) 
Example #27
Source File: PlottingRaster.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def cmap_discretize(self, cmap, N):
        """
        Return a discrete colormap from the continuous colormap cmap.
        From http://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/ColormapTransformations

        Args:
             cmap: colormap instance, eg. cm.jet.
             N: number of colors.

        Returns:
            discrete colourmap

        Author: FJC

        """

        if type(cmap) == str:
         cmap = plt.get_cmap(cmap)

        colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
        colors_rgba = cmap(colors_i)
        indices = np.linspace(0, 1., N+1)
        cdict = {}

        for ki,key in enumerate(('red','green','blue')):
         cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1) ]

        # Return colormap object.
        return _mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024) 
Example #28
Source File: cm.py    From Computable with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from it's name *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize) 
Example #29
Source File: cm.py    From Computable with MIT License 5 votes vote down vote up
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 
Example #30
Source File: cm.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _generate_cmap(name, lutsize):
    """Generates the requested cmap from it's name *name*.  The lut size is
    *lutsize*."""

    spec = datad[name]

    # Generate the colormap object.
    if 'red' in spec:
        return colors.LinearSegmentedColormap(name, spec, lutsize)
    else:
        return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)