示例#1
0
def _has_cmap(dataview):
    """Checks whether a given dataview has colormap (cmap) information as an
    instance or is an RGB volume and does not have a cmap.
    Returns a dictionary with cmap information for non RGB volumes"""

    from matplotlib import colors, cm, pyplot as plt

    cmapdict = dict()
    if not isinstance(dataview, (dataset.VolumeRGB, dataset.VertexRGB)):
        # Get colormap from matplotlib or pycortex colormaps
        ## -- redundant code, here and in cortex/dataset/views.py -- ##
        if isinstance(dataview.cmap,(str,unicode)):
            if not dataview.cmap in cm.__dict__:
                # unknown colormap, test whether it's in pycortex colormaps
                cmapdir = config.get('webgl', 'colormaps')
                colormaps = glob.glob(os.path.join(cmapdir, "*.png"))
                colormaps = dict(((os.path.split(c)[1][:-4],c) for c in colormaps))
                if not dataview.cmap in colormaps:
                    raise Exception('Unkown color map!')
                I = plt.imread(colormaps[dataview.cmap])
                cmap = colors.ListedColormap(np.squeeze(I))
                # Register colormap while we're at it
                cm.register_cmap(dataview.cmap,cmap)
            else:
                cmap = dataview.cmap
        elif isinstance(dataview.cmap,colors.Colormap):
            # Allow input of matplotlib colormap class
            cmap = dataview.cmap

        cmapdict.update(cmap=cmap, 
                        vmin=dataview.vmin, 
                        vmax=dataview.vmax)

    return cmapdict
示例#2
0
def register_map():
    startcolor = '#002200'  # a dark olive
    midcolor = '#008800'  # a bright yellow
    endcolor = '#00FF00'  # medium dark red
    cmap2 = col.LinearSegmentedColormap.from_list(
        'linear_density', [startcolor, midcolor, endcolor])
    cm.register_cmap(cmap=cmap2)
示例#3
0
def register_seismic__cmap(zmin, zmax):
    """Registers `seismic_` diverging color map just suited for data."""

    diff = zmax - zmin
    w = np.abs(zmin / diff)  # white color point set to zero z value

    _cdict = {'red': ((0, 0.0, 0.0),
                      (w / 2, 0.0, 0.0),
                      (w, 1.0, 1.0),
                      (1.5 * w, 1.0, 1.0),
                      (1.0, 0.2, 0.2)),

              'green': ((0.0, 0, 0),
                        (w / 2, 0.0, 0.0),
                        (w, 1.0, 1.0),
                        (1.5 * w, 0.0, 0.0),
                        (1.0, 0.0, 0.0)),

              'blue': ((0.0, 0.2, 0.2),
                       (w / 2, 1.0, 1.0),
                       (w, 1.0, 1.0),
                       (1.5 * w, 0.0, 0.0),
                       (1.0, 0.0, 0.0))
              }

    custom_cmap = LinearSegmentedColormap('seismic_', _cdict)
    cm.register_cmap('seismic_', custom_cmap)
示例#4
0
def register_div_cmap(zmin, zmax):
    """Registers `diverging` diverging color map just suited for data."""

    diff = zmax - zmin
    w = np.abs(zmin / diff)  # white color point set to zero z value

    _cdict = {'red': ((0.0, 0.0, 0.0),
                      (w / 2, 0.0, 0.0),
                      (w, 1.0, 1.0),
                      (w + (1 - w) / 3, 1.0, 1.0),
                      (w + (1 - w) * 2 / 3, 1.0, 1.0),
                      (1.0, 0.3, 0.3)),

              'green': ((0.0, 0, 0),
                        (w / 2, 0.0, 0.0),
                        (w, 1.0, 1.0),
                        (w + (1 - w) / 3, 1.0, 1.0),
                        (w + (1 - w) * 2 / 3, 0.0, 0.0),
                        (1.0, 0.0, 0.0)),

              'blue': ((0.0, 0.3, 0.3),
                       (w / 2, 1.0, 1.0),
                       (w, 1.0, 1.0),
                       (w + (1 - w) / 3, 0.0, 0.0),
                       (w + (1 - w) * 2 / 3, 0.0, 0.0),
                       (1.0, 0.0, 0.0))
              }

    custom_cmap = LinearSegmentedColormap('diverging', _cdict)
    cm.register_cmap('diverging', custom_cmap)
示例#5
0
def green(N=256,gamma=0.4):
    'Returns and registers \'tcmap_green\' colormap.'
    cdict = { 'red': ((0,0.42,0.42),(0.5,0.42,0.42),(1,0.294,0.294)), 'green': ((0,0.59,0.59),(0.5,0.59,0.59),(1,0.413,0.413)), 'blue': ((0,0,0),(1,0,0)) }
    m = clrs.LinearSegmentedColormap('tcmap_green',cdict,N=N)
    m = vary(m,gamma=gamma)
    cm.register_cmap(cmap=m)
    return m
示例#6
0
def get_cmap(cmap_name):
    """Return matplotlib colormap object.

    From matplotlib.cm or cmocean.
    Additional custom colormap for salinity is provided:
    - "custom_salinity1"
    """
    cm.register_cmap(name='cubehelix3',
                     data=mpl._cm.cubehelix(gamma=1.0, s=2.0, r=1.0, h=3))

    if cmap_name in cmo.cmapnames:
        colormap = cmo.cmap_d[cmap_name]
    elif cmap_name in plt.colormaps():
        colormap = plt.get_cmap(cmap_name)
    elif cmap_name == "custom_salinity1":
        colormap = shiftedcolormap(cm.get_cmap("cubehelix3"),
                                   start=0,
                                   midpoint=0.89,
                                   stop=0.9,
                                   name='shiftedcmap')
    else:
        raise ValueError('Get unrecognised name for the colormap `{}`.\
                            Colormaps should be from standard matplotlib \
                            set or from cmocean package.'.format(cmap_name))
    return colormap
示例#7
0
def add_colormap(name, cdict):
    """
    Adds a colormap to the colormaps available in yt for this session
    """
    # Note: this function modifies the global variable 'yt_colormaps'
    yt_colormaps[name] = cc.LinearSegmentedColormap(name, cdict, 256)
    mcm.register_cmap(name, yt_colormaps[name])
def register_ds9staircase():
    # register color map

    colors = []
    for ii in range(1, 6):
        kk = ii / 5.
        colors.append((kk * .3, kk * .3, kk * 1))

    for ii in range(1, 6):
        kk = ii / 5.
        colors.append((kk * .3, kk * 1, kk * .3))
    for ii in range(1, 6):
        kk = ii / 5.
        colors.append((kk * 1, kk * .3, kk * .3))
    colors = np.array(colors)
    xx = np.arange(len(colors), dtype=float)
    xx = xx / xx.max()

    ds9staircase = {
        'red': lambda v: np.interp(v, xx, colors[:, 0]),
        'green': lambda v: np.interp(v, xx, colors[:, 1]),
        'blue': lambda v: np.interp(v, xx, colors[:, 2])
    }

    # Register all other colormaps
    register_cmap('ds9staircase', data=ds9staircase)
示例#9
0
    def build(self):
        self.fig.subplots_adjust(left=0, right=1.0, top=1.0, bottom=0)
        ax = self.fig.add_subplot(111)
        ax.axis('scaled')
        ax.axis([0, self.w, 0, self.h])
        ax.xaxis.set_major_formatter(plt.NullFormatter())
        ax.yaxis.set_major_formatter(plt.NullFormatter())

        ###
        if self.wb == 'wb':
            self.alpha_cm = [
                tuple(map(float, e.split(','))) for e in self.alpha_cm
            ]
            cm.register_cmap(name='new',
                             data={
                                 'red': [(0., 0., 0.), (1., 1., 1.)],
                                 'blue': [(0., 0., 0.), (1., 1., 1.)],
                                 'green': [(0., 0., 0.), (1., 1., 1.)],
                                 'alpha': self.alpha_cm
                             })
        elif self.wb == 'bw':
            self.alpha_cm = [
                tuple(map(float, e.split(','))) for e in self.alpha_cm
            ]
            cm.register_cmap(name='new',
                             data={
                                 'red': [(0., 1., 1.), (1., 0., 0.)],
                                 'blue': [(0., 1., 1.), (1., 0., 0.)],
                                 'green': [(0., 1., 1.), (1., 0., 0.)],
                                 'alpha': self.alpha_cm
                             })
示例#10
0
def blue(N=256,gamma=0.4):
    'Returns and registers \'tcmap_blue\' colormap.'
    cdict = { 'red': ((0,0,0),(1,0,0)), 'green': ((0,0.61,0.61),(0.5,0.61,0.61),(1,0.427,0.427)), 'blue': ((0,1,1),(0.5,1,1),(1,0.7,0.7)) }
    m = clrs.LinearSegmentedColormap('tcmap_blue',cdict,N=N)
    m = vary(m,gamma=gamma)
    cm.register_cmap(cmap=m)
    return m
示例#11
0
 def raw(self):
     from matplotlib import colors, cm, pyplot as plt
     import glob, os
     # Get colormap from matplotlib or pycortex colormaps
     ## -- redundant code, here and in cortex/quicklflat.py -- ##
     if isinstance(self.cmap, string_types):
         if not self.cmap in cm.__dict__:
             # unknown colormap, test whether it's in pycortex colormaps
             cmapdir = options.config.get('webgl', 'colormaps')
             colormaps = glob.glob(os.path.join(cmapdir, "*.png"))
             colormaps = dict(((os.path.split(c)[1][:-4],c) for c in colormaps))
             if not self.cmap in colormaps:
                 raise Exception('Unkown color map!')
             I = plt.imread(colormaps[self.cmap])
             cmap = colors.ListedColormap(np.squeeze(I))
             # Register colormap while we're at it
             cm.register_cmap(self.cmap,cmap)
         else:
             cmap = cm.get_cmap(self.cmap)
     elif isinstance(self.cmap, colors.Colormap):
         cmap = self.cmap
     # Normalize colors according to vmin, vmax
     norm = colors.Normalize(self.vmin, self.vmax) 
     cmapper = cm.ScalarMappable(norm=norm, cmap=cmap)
     color_data = cmapper.to_rgba(self.data.flatten()).reshape(self.data.shape+(4,))
     # rollaxis puts the last color dimension first, to allow output of separate channels: r,g,b,a = dataset.raw
     return np.rollaxis(color_data, -1)
示例#12
0
def orange(N=256,gamma=0.4):
    'Returns and registers \'tcmap_orange\' colormap.'
    cdict = { 'red': ((0,1,1),(0.5,1,1),(1,0.7,0.7)), 'green': ((0,0.28,0.28),(0.5,0.28,0.28),(1,0.196,0.196)), 'blue': ((0,0.07,0.07),(0.5,0.07,0.07),(1,0.049,0.049)) }
    m = clrs.LinearSegmentedColormap('tcmap_orange',cdict,N=N)
    m = vary(m,gamma=gamma)
    cm.register_cmap(cmap=m)
    return m
示例#13
0
def make_custom_maps():
    # adapted from
    # http://matplotlib.org/examples/pylab_examples/custom_cmap.html
    try:
        from matplotlib import colors, cm
        from matplotlib.colors import LinearSegmentedColormap
    except ImportError as e:
        print("Could not make custom maps")
        return

    cdict1 = {
        'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)),
        'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0))
    }

    cdict2 = {
        'red':
        ((0.0, 0.0, 0.0), (0.35, 1.0, 1.0), (0.65, 1.0, 1.0), (1.0, 1.0, 1.0)),
        'green': ((0.0, 0.0, 0.0), (0.35, 0.95, 0.95), (0.65, 0.95, 0.95),
                  (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 0.1), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0))
    }

    cm.register_cmap(name='BlueRed1', data=cdict1)
    cm.register_cmap(name='Belgium', data=cdict2)
示例#14
0
def make_cmap_from_RGB(name='BlueYellowRed'):
    '''
    Create a colormap from a RGB file
    This is particularly useful when you can download an exotic
    RGB file off the internet
    '''

    dir_rgb = '/home/rmahajan/svn-work/python_lib/colormaps'
    filename = '%s/%s.rgb' % (dir_rgb, name)

    try:
        palette = open(filename)
    except IOError:
        raise IOError('Cannot read RGB file for %s from %s' % (name, dir_rgb))

    lines = palette.readlines()
    ncolors = len(lines)

    carray = _np.zeros([ncolors, 3])
    for num, line in enumerate(lines):
        carray[num, :] = [float(val) / 255.0 for val in line.strip().split()]
    cmap = _colors.ListedColormap(carray, name=name)
    _cm.register_cmap(name=name, cmap=cmap)

    return cmap
示例#15
0
    def register(self) -> Colormap:
        '''
        Create a linear-segmented colormap from the current scheme, register
        this colormap with matplotlib, and return this colormap.
        '''

        # Log this registration attempt.
        # logs.log_debug(
        #     'Registering colormap "%s": %s',
        #     self.colormap_name, self.colors_normalized)

        # Two-dimensional Numpy array, normalizing each of each color's values
        # from [0, 255] to [0.0, 1.0] (while preserving the order of colors).
        colors_normalized = np.array(self._colors) / 255

        # Colormap synthesized from this colormap name and colors.
        #
        # Unfortunately, as the names of the first two parameters accepted by
        # this function have changed across matplotlib versions, these
        # parameters *MUST* be passed positionally for safety.
        colormap = LinearSegmentedColormap.from_list(self._name,
                                                     colors_normalized,
                                                     N=256,
                                                     gamma=self._gamma)

        # Register this colormap with matplotlib.
        colormaps.register_cmap(cmap=colormap)

        # Return this colormap.
        return colormap
示例#16
0
def rsmctoa_cmap():
    '''
    Generate colour map for arrival times.
    First color must be grey

    >>> cmap = rsmctoa_cmap()

    To plot and display colour map:

    >>> import config
    >>> import plotting_functions
    >>> filename = config.CODE_DIR + "/adaqdocs/figures/rsmctoa_cmap.png"
    >>> plotting_functions.plot_cmap(cmap, filename=filename)
    ... # doctest: +ELLIPSIS
    Saved figure .../rsmctoa_cmap.png

    .. image:: ../adaqdocs/figures/rsmctoa_cmap.png
       :scale: 50%
    '''
    # pylint: disable=bad-whitespace
    colours = [[224, 224, 224], [215, 48, 31], [252, 141, 89], [253, 204, 138],
               [254, 240, 217]]
    # pylint: enable=bad-whitespace
    colours = np.array(colours) / 255.
    cmap = colors.ListedColormap(colours, name='RSMCTOA')

    #Register colour map, so can be called
    # eg plt.get_cmap('RSMCTOA')
    cm.register_cmap(cmap=cmap)

    return cmap
def make_cmap(colors, name="custom", position=None, bit=False):
    """
    modified from http://schubert.atmos.colostate.edu/~cslocum/custom_cmap.html
    make_cmap takes a list of tuples which contain RGB values. The RGB
    values may either be in 8-bit [0 to 255] (in which bit must be set to
    True when called) or arithmetic [0 to 1] (default). make_cmap returns
    a cmap with equally spaced colors.
    Arrange your tuples so that the first color is the lowest value for the
    colorbar and the last is the highest.
    position contains values from 0 to 1 to dictate the location of each color.
    """
    import matplotlib as mpl
    import matplotlib.cm as cm
    import numpy as np

    bit_rgb = np.linspace(0, 1, 256)
    if position == None:
        position = np.linspace(0, 1, len(colors))
    else:
        if len(position) != len(colors):
            sys.exit("position length must be the same as colors")
        elif position[0] != 0 or position[-1] != 1:
            sys.exit("position must start with 0 and end with 1")
    if bit:
        for i in range(len(colors)):
            colors[i] = (bit_rgb[colors[i][0]], bit_rgb[colors[i][1]], bit_rgb[colors[i][2]])
    cdict = {"red": [], "green": [], "blue": []}
    for pos, color in zip(position, colors):
        cdict["red"].append((pos, color[0], color[0]))
        cdict["green"].append((pos, color[1], color[1]))
        cdict["blue"].append((pos, color[2], color[2]))

    cmap = mpl.colors.LinearSegmentedColormap("custom", cdict, 256)
    cm.register_cmap(name="custom", cmap=cmap)
    return cmap
示例#18
0
 def initsca(self,t='fig'):#绘图数据读取
     startcolor = '#005EFF'   
     midcolor = '#2CFF4B'    
     endcolor = '#F43931'         
     self.cmap2 = col.LinearSegmentedColormap.from_list('own2',[startcolor,midcolor,endcolor]) 
     cm.register_cmap(cmap=self.cmap2)
     if t=='fig':
         self.point=np.zeros([200,200,6,2])
         csvfile=csv.reader(open(self.path+'\说明\draw\draw.csv','r'))
         m=True
         for line in csvfile:
             if m:
                 i=int(line[0])-1
                 j=int(line[1])-1
                 m=False
             else:
                 m=True
                 for k in range(6):
                     self.point[i][j][k][0]=int(line[k*2])-1
                     self.point[i][j][k][1]=float(line[k*2+1])
     if t=='tri':
         csvfile=csv.reader(open(self.path+'\说明\draw\draw1.csv','r'))
         self.point=np.zeros([200,200])
         for line in csvfile:
             i=int(line[0])-1
             j=int(line[1])-1
             self.point[i][j]=int(line[2])-1
示例#19
0
def cams_cmap():
    '''
    Generate colour map based on DAQI colours

    >>> cmap = cams_cmap()

    To plot and display colour map:

    >>> import config
    >>> import plotting_functions
    >>> filename = config.CODE_DIR + "/adaqdocs/figures/cams_cmap.png"
    >>> plotting_functions.plot_cmap(cmap, filename=filename)
    ... # doctest: +ELLIPSIS
    Saved figure .../cams_cmap.png

    .. image:: ../adaqdocs/figures/cams_cmap.png
       :scale: 50%

    '''

    #rgb colours [ [red, green, blue], [r,g,b],... ]
    colours = [[220, 220, 220], [18, 101, 209], [38, 129, 240], [79, 165, 244],
               [0, 220, 0], [80, 240, 80], [160, 229, 48], [229, 220, 49],
               [229, 175, 45], [240, 126, 38], [250, 60, 60], [240, 0, 132]]
    colours = np.array(colours) / 255.
    cmap = colors.ListedColormap(colours, name='CAMS')

    #Register colour map, so can be called
    # eg plt.get_cmap('CAMS')
    cm.register_cmap(cmap=cmap)

    return cmap
示例#20
0
def red(N=256,gamma=0.4):
    'Returns and registers \'tcmap_red\' colormap.'
    cdict = { 'red': ((0,1,1),(0.5,1,1),(1,0.7,0.7)), 'green': ((0,0.237,0.237),(0.5,0.237,0.237),(1,0.166,0.166)), 'blue': ((0,0.3,0.3),(0.5,0.3,0.3),(1,0.21,0.21)) }
    m = clrs.LinearSegmentedColormap('tcmap_red',cdict,N=N)
    m = vary(m,gamma=gamma)
    cm.register_cmap(cmap=m)
    return m
示例#21
0
def register_div_white_cmap(zmin, zmax, treshold=0.98):
    """Registers `diverging` diverging color map just suited for data.

    With extra white space at around zero - for filled countours colormaps to ensure zero is white."""

    diff = zmax - zmin
    w = np.abs(zmin / diff)  # white color point set to zero z value

    tr = treshold

    _cdict = {
        'red':
        ((0.0, 0.0, 0.0), (w / 2, 0.0, 0.0), (w * tr, 1.0, 1.0),
         (w + (1 - w) * (1 - tr), 1.0, 1.0), (w + (1 - w) / 3, 1.0, 1.0),
         (w + (1 - w) * 2 / 3, 1.0, 1.0), (1.0, 0.3, 0.3)),
        'green':
        ((0.0, 0, 0), (w / 2, 0.0, 0.0), (w * tr, 1.0, 1.0),
         (w + (1 - w) * (1 - tr), 1.0, 1.0), (w + (1 - w) / 3, 1.0, 1.0),
         (w + (1 - w) * 2 / 3, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'blue':
        ((0.0, 0.3, 0.3), (w / 2, 1.0, 1.0), (w * tr, 1.0, 1.0),
         (w + (1 - w) * (1 - tr), 1.0, 1.0), (w + (1 - w) / 3, 0.0, 0.0),
         (w + (1 - w) * 2 / 3, 0.0, 0.0), (1.0, 0.0, 0.0))
    }

    custom_cmap = LinearSegmentedColormap('diverging_white_tr', _cdict)
    cm.register_cmap('diverging_white_tr', custom_cmap)
示例#22
0
def plot_mask(mask, plotAxis=None, color='#ff0000', zoom=1, borderWidth=None, closingIteration=None):
    """
    plot mask borders in a given color
    """

    if not plotAxis:
        f = plt.figure()
        plotAxis = f.add_subplot(111)

    cmap1 = col.ListedColormap(color, 'temp')
    cm.register_cmap(cmap=cmap1)

    if zoom != 1:
        mask = ni.interpolation.zoom(mask, zoom, order=0)

    mask2 = mask.astype(np.float32)
    mask2[np.invert(np.isnan(mask2))] = 1.
    mask2[np.isnan(mask2)] = 0.

    struc = ni.generate_binary_structure(2, 2)
    if borderWidth:
        border = mask2 - ni.binary_erosion(mask2, struc, iterations=borderWidth).astype(np.float32)
    else:
        border = mask2 - ni.binary_erosion(mask2, struc).astype(np.float32)

    if closingIteration:
        border = ni.binary_closing(border, iterations=closingIteration).astype(np.float32)

    border[border == 0] = np.nan

    currfig = plotAxis.imshow(border, cmap='temp', interpolation='nearest')

    return currfig
示例#23
0
 def test_get_cmaps_registers_snap_color(self):
     ensure_cmaps_loaded()
     cmap_name = os.path.join(os.path.dirname(__file__), 'chl_DeM2_200.cpd')
     cmap = _get_custom_colormap(cmap_name)
     cm.register_cmap(cmap=cmap)
     self.assertTrue((type(cmap) is LinearSegmentedColormap)
                     or (type(cmap) is ListedColormap))
示例#24
0
def _has_cmap(dataview):
    """Checks whether a given dataview has colormap (cmap) information as an
    instance or is an RGB volume and does not have a cmap.
    Returns a dictionary with cmap information for non RGB volumes"""

    from matplotlib import colors, cm, pyplot as plt

    cmapdict = dict()
    if not isinstance(dataview, (dataset.VolumeRGB, dataset.VertexRGB)):
        # Get colormap from matplotlib or pycortex colormaps
        ## -- redundant code, here and in cortex/dataset/views.py -- ##
        if isinstance(dataview.cmap, (str, unicode)):
            if not dataview.cmap in cm.__dict__:
                # unknown colormap, test whether it's in pycortex colormaps
                cmapdir = config.get('webgl', 'colormaps')
                colormaps = glob.glob(os.path.join(cmapdir, "*.png"))
                colormaps = dict(
                    ((os.path.split(c)[1][:-4], c) for c in colormaps))
                if not dataview.cmap in colormaps:
                    raise Exception('Unkown color map!')
                I = plt.imread(colormaps[dataview.cmap])
                cmap = colors.ListedColormap(np.squeeze(I))
                # Register colormap while we're at it
                cm.register_cmap(dataview.cmap, cmap)
            else:
                cmap = dataview.cmap
        elif isinstance(dataview.cmap, colors.Colormap):
            # Allow input of matplotlib colormap class
            cmap = dataview.cmap

        cmapdict.update(cmap=cmap, vmin=dataview.vmin, vmax=dataview.vmax)

    return cmapdict
示例#25
0
def rsmcgrey_cmap():
    '''
    Generate colour map for faxing.
    All colours are shades of grey

    >>> cmap = rsmcgrey_cmap()

    To plot and display colour map:

    >>> import config
    >>> import plotting_functions
    >>> filename = config.CODE_DIR + "/adaqdocs/figures/rsmcgrey_cmap.png"
    >>> plotting_functions.plot_cmap(cmap, filename=filename)
    ... # doctest: +ELLIPSIS
    Saved figure .../rsmcgrey_cmap.png

    .. image:: ../adaqdocs/figures/rsmcgrey_cmap.png
       :scale: 50%
    '''
    # pylint: disable=bad-whitespace
    colours = [[192, 192, 192], [128, 128, 128], [64, 64, 64], [0, 0, 0]]
    # pylint: enable=bad-whitespace
    colours = np.array(colours) / 255.
    cmap = colors.ListedColormap(colours, name='RSMCGREY')

    #Register colour map, so can be called
    # eg plt.get_cmap('RSMCGREY')
    cm.register_cmap(cmap=cmap)

    return cmap
示例#26
0
def test_double_register_builtin_cmap():
    name = "viridis"
    match = f"Trying to re-register the builtin cmap {name!r}."
    with pytest.raises(ValueError, match=match):
        cm.register_cmap(name, cm.get_cmap(name))
    with pytest.warns(UserWarning):
        cm.register_cmap(name, cm.get_cmap(name), override_builtin=True)
示例#27
0
 def raw(self):
     from matplotlib import colors, cm, pyplot as plt
     import glob, os
     # Get colormap from matplotlib or pycortex colormaps
     ## -- redundant code, here and in cortex/quicklflat.py -- ##
     if isinstance(self.cmap, string_types):
         if not self.cmap in cm.__dict__:
             # unknown colormap, test whether it's in pycortex colormaps
             cmapdir = options.config.get('webgl', 'colormaps')
             colormaps = glob.glob(os.path.join(cmapdir, "*.png"))
             colormaps = dict(
                 ((os.path.split(c)[1][:-4], c) for c in colormaps))
             if not self.cmap in colormaps:
                 raise Exception('Unkown color map!')
             I = plt.imread(colormaps[self.cmap])
             cmap = colors.ListedColormap(np.squeeze(I))
             # Register colormap while we're at it
             cm.register_cmap(self.cmap, cmap)
         else:
             cmap = cm.get_cmap(self.cmap)
     elif isinstance(self.cmap, colors.Colormap):
         cmap = self.cmap
     # Normalize colors according to vmin, vmax
     norm = colors.Normalize(self.vmin, self.vmax)
     cmapper = cm.ScalarMappable(norm=norm, cmap=cmap)
     color_data = cmapper.to_rgba(
         self.data.flatten()).reshape(self.data.shape + (4, ))
     # rollaxis puts the last color dimension first, to allow output of separate channels: r,g,b,a = dataset.raw
     return np.rollaxis(color_data, -1)
示例#28
0
def from_ascii(filename, name):
    '''Creates a ListedColormap instance and registers it in the current python
    session.  Note: Will have to be re-registered in all new python sessions.

    Inputs:
        filename - Full path to a three column ascii file whose contents must
                   be floats that either range from 0.0-1.0 or from 0-255.
        name - Name of the colorbar for registration and later recall.
    '''
    #Read data from ascii file into an NLines by 3 float array
    palette = open(filename)
    lines = palette.readlines()
    palette.close()
    carray = np.zeros([len(lines), 3])
    for num, line in enumerate(lines):
        carray[num, :] = [float(val) for val in line.strip().split()]

    #Normalize from 0-255 to 0.0-1.0
    if carray.max() > 1.0:
        carray /= 255.0

    #Test to be sure all color array values are between 0.0 and 1.0
    if not (carray.min() >= 0.0 and carray.max() <= 1.0):
        raise ValueError('All values in carray must be between 0.0 and 1.0.')

    if name[-2:] == '_r':
        carray = np.flipud(carray)

    #Create colormap instance and register for further use in this python session
    cmap = colors.ListedColormap(carray, name=name)
    cm.register_cmap(name=str(name), cmap=cmap)
    return cmap
示例#29
0
 def test_get_cmaps_registers_ivalid_snap_color(self):
     ensure_cmaps_loaded()
     cmap_name = os.path.join(os.path.dirname(__file__),
                              'chl_DeM2_200_invalid_for_testing.cpd')
     with self.assertRaises(ValueError):
         cmap = _get_custom_colormap(cmap_name)
         cm.register_cmap(cmap=cmap)
示例#30
0
def colormapreg_byimgfile(imgfile, quantlv=256, gamma=1.0):
    """ Criação/registro de colormap a partir de arquivo de imagem. """

    # Carregamento da imagem.
    img = mimg.imread(imgfile)

    # Exclusão do canal 'A (alpha) da composição RGBA (caso exista).
    if img.shape[-1] == 4:
        cmapcolors = img[:, 0, 0:-1]
    else:
        cmapcolors = img[:, 0, :]

    # Registro do colormap (sentido original).
    cmapname = osp.basename(imgfile).split('_')[0]
    mcm.datad[cmapname] = flipud(cmapcolors)

    mcm.register_cmap(cmap=mcm.colors.LinearSegmentedColormap.from_list(
        cmapname, mcm.datad[cmapname], quantlv, gamma))

    # Registro do colormap (sentido reverso).
    cmapname = osp.basename(imgfile).split('_')[0] + '_r'
    mcm.datad[cmapname] = cmapcolors

    mcm.register_cmap(cmap=mcm.colors.LinearSegmentedColormap.from_list(
        cmapname, mcm.datad[cmapname], quantlv, gamma))
示例#31
0
def daqi_cmap():
    '''
    Generate colour map based on DAQI colours

    >>> cmap = daqi_cmap()

    To plot and display colour map:

    >>> import config
    >>> import plotting_functions
    >>> filename = config.CODE_DIR + "/adaqdocs/figures/daqi_cmap.png"
    >>> plotting_functions.plot_cmap(cmap, filename=filename)
    ... # doctest: +ELLIPSIS
    Saved figure .../daqi_cmap.png

    .. image:: ../adaqdocs/figures/daqi_cmap.png
       :scale: 50%
    '''
    # pylint: disable=bad-whitespace
    colours = [[156, 255, 156], [49, 255, 0], [49, 207, 0], [255, 255, 0],
               [255, 207, 0], [255, 154, 0], [255, 100, 100], [255, 0, 0],
               [153, 0, 0], [206, 48, 255]]
    # pylint: enable=bad-whitespace
    colours = np.array(colours) / 255.
    cmap = colors.ListedColormap(colours, name='DAQI')

    #Register colour map, so can be called
    # eg plt.get_cmap('DAQI')
    cm.register_cmap(cmap=cmap)

    return cmap
def make_my_cmaps():
    # surface density color map
    x = [-4.11 - sdoff, -3.11 - sdoff, -.931 - sdoff, .069 - sdoff]
    # x[3] and x[0] are cdmax and cdmin below.
    beginx = (x[1] - x[0]) / (x[3] - x[0])
    begingray = 0.9
    transitionx = (x[2] - x[0]) / (x[3] - x[0])
    transitiongray = 0.35
    finishr = 37 / 256
    finishg = 49 / 256
    finishb = 111 / 256
    cdict = {'red': ((0.0, 1.0, 1.0),
                     (beginx, begingray, begingray),
                     (transitionx, transitiongray, transitiongray),
                     (1.0, finishr, finishr)),
           'green': ((0.0, 1.0, 1.0),
                     (beginx, begingray, begingray),
                     (transitionx, transitiongray, transitiongray),
                     (1.0, finishg, finishg)),
            'blue': ((0.0, 1.0, 1.0),
                     (beginx, begingray, begingray),
                     (transitionx, transitiongray, transitiongray),
                     (1.0, finishb, finishb))}      
    cmap1 = col.LinearSegmentedColormap('my_colormapSD', cdict, N=256, gamma=1.0)
    cm.register_cmap(name='nickmapSD', cmap=cmap1)
示例#33
0
def rsmcac_cmap():
    '''
    Generate colour map based on Toulouse air concentration map

    >>> cmap = rsmcac_cmap()

    To plot and display colour map:

    >>> import config
    >>> import plotting_functions
    >>> filename = config.CODE_DIR + "/adaqdocs/figures/rsmcac_cmap.png"
    >>> plotting_functions.plot_cmap(cmap, filename=filename)
    ... # doctest: +ELLIPSIS
    Saved figure .../rsmcac_cmap.png

    .. image:: ../adaqdocs/figures/rsmcac_cmap.png
       :scale: 50%
    '''
    # pylint: disable=bad-whitespace
    colours = [[254, 252, 106], [250, 205, 87], [200, 150, 29], [149, 89, 9]]
    # pylint: enable=bad-whitespace
    colours = np.array(colours) / 255.
    cmap = colors.ListedColormap(colours, name='RSMCAC')

    #Register colour map, so can be called
    # eg plt.get_cmap('RSMCAC')
    cm.register_cmap(cmap=cmap)

    return cmap
def choi_cmaps():
    # Creating custom colour palette based on Choi 2012
    # Colours in order: Purple, Blue, Green, Violet, Cream, Orange, Red
    # These are the RGB values defined in the colorLUT.txt
    choi_col = np.array([(120, 18, 134), (70, 130, 180), (0, 118, 14),
                         (196, 58, 250), (220, 248, 164), (230, 148, 34),
                         (205, 62, 78)]) / 255
    # Use matplotlib.colors.to_hex to get hex values
    choi_lut = [
        '#800080', '#0000ff', '#008000', '#ee82ee', '#eee8aa', '#ffa500',
        '#ff0000'
    ]

    choi_style = dict()

    choi_style['choi_col'] = colors.LinearSegmentedColormap.from_list(
        'choi_col', choi_col.tolist())
    choi_style['choi_lut'] = colors.LinearSegmentedColormap.from_list(
        'choi_lut', choi_lut)

    # Save colormaps in the scope of the module
    locals().update(choi_style)
    # Register cmaps in matplotlib too
    for k, v in choi_style.items():
        cm.register_cmap(name=k, cmap=v)
示例#35
0
def register_lc_color_map():
    lc_color_mappings = [
        (0, dict(r=0, g=0, b=0)),
        (10, dict(r=255, g=255, b=100)),
        (11, dict(r=255, g=255, b=100)),
        (12, dict(r=255, g=255, b=0)),
        (20, dict(r=170, g=240, b=240)),
        (30, dict(r=220, g=240, b=100)),
        (40, dict(r=200, g=200, b=100)),
        (50, dict(r=0, g=100, b=0)),
        (60, dict(r=0, g=160, b=0)),
        (61, dict(r=0, g=160, b=0)),
        (62, dict(r=170, g=200, b=0)),
        (70, dict(r=0, g=60, b=0)),
        (71, dict(r=0, g=60, b=0)),
        (72, dict(r=0, g=80, b=0)),
        (80, dict(r=40, g=80, b=0)),
        (81, dict(r=40, g=80, b=0)),
        (82, dict(r=40, g=100, b=0)),
        (90, dict(r=120, g=130, b=0)),
        (100, dict(r=140, g=160, b=0)),
        (110, dict(r=190, g=150, b=0)),
        (120, dict(r=150, g=100, b=0)),
        (121, dict(r=120, g=75, b=0)),
        (122, dict(r=150, g=100, b=0)),
        (130, dict(r=255, g=180, b=50)),
        (140, dict(r=255, g=220, b=210)),
        (150, dict(r=255, g=235, b=175)),
        (151, dict(r=255, g=205, b=120)),
        (152, dict(r=255, g=210, b=120)),
        (153, dict(r=255, g=235, b=175)),
        (160, dict(r=0, g=120, b=190)),
        (170, dict(r=0, g=150, b=120)),
        (180, dict(r=0, g=220, b=130)),
        (190, dict(r=195, g=20, b=0)),
        (200, dict(r=255, g=245, b=215)),
        (201, dict(r=220, g=220, b=220)),
        (202, dict(r=255, g=245, b=215)),
        (210, dict(r=0, g=70, b=200)),
        (220, dict(r=255, g=255, b=255)),
    ]

    classes = {lc: color for lc, color in lc_color_mappings}

    invalid_rgba = (0, 0, 0, 0.5)
    class_0_rgba = (0, 0, 0, 0)

    rgba_list = []
    num_entries = 256
    last_rgba = invalid_rgba
    for i in range(num_entries):
        color = classes.get(i)
        if color:
            last_rgba = (color['r'] / 255, color['g'] / 255, color['b'] / 255, 1.0)
        rgba_list.append(last_rgba)
    rgba_list[0] = class_0_rgba

    cmap = matplotlib.colors.ListedColormap(rgba_list, name=LAND_COVER_CCI_CMAP, N=num_entries)
    cm.register_cmap(cmap=cmap)
def discrete_cmap(N=8):
    """create a colormap with N (N<15) discrete colors and register it"""
    # define individual colors as hex values
    cpool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',
              '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',
              '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]
    cmap3 = col.ListedColormap(cpool[0:N], 'indexed')
    cm.register_cmap(cmap=cmap3)
示例#37
0
def register_cmap_safe(name, data):
    "Register a colormap if not already registered."
    try:
        return cm.get_cmap(name)
    except ValueError:
        cmap = LinearSegmentedColormap.from_list(name, data)
        cm.register_cmap(name, cmap)
        return cmap
示例#38
0
def draw(map,svg=True,name='',hide=True,colorbar=False,notif=[]):
    """
    Display the map as 2D array, with a specific color for each Cell nature and state
    
    :param map: Map object which must be displayed
    :param svg: boolean, determine if the image must be saved or not
    :param name: string, add an additional name to 'imgXXX.png'
    :param hide: boolean, toggle the display of the drawn image
    :param colorbar: boolean, toggle the colorbar used at the right of the image
    :param notif: string array, contains every notification which must be displayed
    """
    map.calc_mat()      #update the matrix
    mx = int( np.amax(map.map) )      #max and min values of the matrix
    mn = int( np.amin(map.map) )      #to determine the colormap used
    
    
    simu_color = col.ListedColormap(cpool[(mn+1):(mx+2)], 'indexed')
    cm.register_cmap(cmap=simu_color)
    color = simu_color
        
    if(hide): plt.ioff()         #hide the poping windows of python
    else: plt.ion()
    
    if(colorbar): plt.colorbar()     #show the colormap used to draw the matrix
    
    
    #list of displayed fireman on the map, to draw bigger symbols when there is multiple firemen on same cell
    frman_display = []
    for frman in map.fireman_list:
        new = True
        for i in range(len(frman_display)):
            if(frman.x == frman_display[i][0] and frman.y == frman_display[i][1]):       #if there is already a fireman on this position
                new = False
                break
        if(not new): frman_display[i][2] += 1       #size of the symbol whill be bigger
        else: frman_display.append([frman.x,frman.y,0])     #new position to draw a symbol
                
       
    plt.matshow(map.map,cmap=color)     #display the map
    
    for i in range(len(frman_display)):          #display firemen with a red square
        size = 3 + (frman_display[i][2])
        plt.plot(frman_display[i][0],frman_display[i][1],'rs',markersize=size)
    
    for i in range(len(notif)):                 #display the notifications
        plt.text(0,i*2, notif[i], color='w')
        
    wind_dir = ['N','NE','E','SE','S','SW','W','NW']  
    if(map.wind_active): plt.text(0,map.size,'wind: '+ wind_dir[map.wind], color='b')       #display wind notification
    
    plt.text(map.size/2, map.size, str(len(map.fireman_list)) + ' firemen alive', color='r')        #display number of firemen

    plt.axis([-0.5,map.size-0.5,-0.5,map.size-0.5])     #resize the image
    plt.axis('off')                                     #hide the axis
        
    if(svg):
        txt = "images/img" + str(map.count+100) + name + ".png"      #image's name, +100 for index problems (conversion)
        plt.savefig(txt,dpi=200,bbox_inches='tight',pad_inches=0)
示例#39
0
def discrete_cmap(N=7):
    # define individual colors as hex values
    cpool = [ '#FF6E30', '#D05A27', '#AA4920', '#883A19', '#662C13',
              '#311509', '#000000']

    # TODO: build cpool as a sequence of colors of variying value (from 0 to 255) in hsv color space, then convert to hex

    discrete_cmap = col.ListedColormap(cpool[0:N], 'discrete_copper')
    cm.register_cmap(cmap=discrete_cmap)
示例#40
0
    def calculate_em(self, wlen='171', dz=100, model=False):
        """
        Calculate an approximation of the coronal EmissionMeasure using a given
        TemperatureMap object and a particular AIA channel.
    
        Parameters
        ----------
        tmap : CoronaTemps.temperature.TemperatureMap
            A TemperatureMap instance containing coronal temperature data
        wlen : {'94' | '131' | '171' | '193' | '211' | '335'}
            AIA wavelength used to approximate the emission measure. '171', '193'
            and '211' are most likely to provide reliable results. Use of other
            channels is not recommended.
        """
        # Load the appropriate temperature response function
        tresp = read('/imaps/holly/home/ajl7/CoronaTemps/aia_tresp')
        resp = tresp['resp{}'.format(wlen)]
    
        # Get some information from the TemperatureMap and set up filenames, etc
        tempdata = self.data.copy()
        tempdata[np.isnan(tempdata)] = 0.0
        date = sunpy.time.parse_time(self.date)
        if not model:
            data_dir = self.data_dir
            fits_dir = path.join(data_dir, '{:%Y/%m/%d}/{}'.format(date, wlen))
            filename = path.join(fits_dir,
                                 '*{0:%Y?%m?%d}?{0:%H?%M}*fits'.format(date))
            if wlen == '94': filename = filename.replace('94', '094')
    
            # Load and appropriately process AIA data
            filelist = glob.glob(filename)
            if filelist == []:
                print 'AIA data not found :('
                return
            aiamap = Map(filename)
            aiamap.data /= aiamap.exposure_time
            aiamap = aiaprep(aiamap)
            aiamap = aiamap.submap(self.xrange, self.yrange)
        else:
            fname = '/imaps/holly/home/ajl7/CoronaTemps/data/synthetic/{}/model.fits'.format(wlen)
            if wlen == '94': fname = fname.replace('94', '094')
            aiamap = Map(fname)

        # Create new Map and put EM values in it
        emmap = Map(self.data.copy(), self.meta.copy())
        indices = np.round((tempdata - 4.0) / 0.05).astype(int)
        indices[indices < 0] = 0
        indices[indices > 100] = 100
        #print emmap.shape, indices.shape, tempdata.shape, aiamap.shape, resp.shape
        emmap.data = np.log10(aiamap.data / resp[indices])
        #emmap.data = aiamap.data / resp[indices]

        emmapcubehelix = _cm.cubehelix(s=2.8, r=-0.7, h=1.4, gamma=1.0)
        cm.register_cmap(name='emhelix', data=emmapcubehelix)
        emmap.cmap = cm.get_cmap('emhelix')
    
        return emmap
示例#41
0
文件: cbook.py 项目: piScope/piScope
def register_idl_colormaps():
    from matplotlib.cm import register_cmap
    names = []
    for x in range(40):
       cmap = loadct(x)
       name = 'idl'+str(x)
       register_cmap(name = name, cmap = cmap)
       names.append(name)
    return names
示例#42
0
def discrete_cmap(N=14):
    # define individual colors as hex values
    cpool = [ '#FFC57E', '#FFB573', '#FEA167', '#EE9760', '#D88758', '#BF794D', '#A66943', '#8F5A39', '#76492E', '#5F3C26', '#492D1D', '#2F1D13',
              '#1A0F0A', '#000000']
    cpool = cpool[::-1]

    # TODO: build cpool as a sequence of colors of variying value (from 0 to 255) in hsv color space, then convert to hex

    discrete_cmap = col.ListedColormap(cpool[0:N], 'discrete_copper')
    cm.register_cmap(cmap=discrete_cmap)
示例#43
0
def james2():
    """David James suggested color ramp Yellow to Brown"""
    cpool = ['#FFFF80', '#FFEE70', '#FCDD60', '#FACD52', '#F7BE43', '#F5AF36',
             '#E69729', '#CC781F', '#B35915', '#9C400E', '#822507', '#6B0000']
    cmap3 = mpcolors.ListedColormap(cpool, 'james2')
    cmap3.set_over("#000000")
    cmap3.set_under("#FFFFFF")
    cmap3.set_bad("#FFFFFF")
    cm.register_cmap(cmap=cmap3)
    return cmap3
示例#44
0
def james():
    """David James suggested color ramp Yellow to Blue """
    cpool = ['#FFFF80', '#CDFA64', '#98F046', '#61E827', '#3BD923', '#3FC453',
             '#37AD7A', '#26989E', '#217AA3', '#215394', '#1B3187', '#0C1078']
    cmap3 = mpcolors.ListedColormap(cpool, 'james')
    cmap3.set_over("#000000")
    cmap3.set_under("#FFFFFF")
    cmap3.set_bad("#FFFFFF")
    cm.register_cmap(cmap=cmap3)
    return cmap3
示例#45
0
文件: core.py 项目: adrn/streams
def discrete_cmap(N=8):
    """create a colormap with N (N<15) discrete colors and register it"""
    # define individual colors as hex values
    # #9E0142
    cpool = ['#D085A4', '#D53E4F', '#F46D43', '#FDAE61', '#FEE08B',
             '#E6F598', '#ABDDA4', '#66C2A5', '#3288BD', '#5E4FA2']
    if N == 5:
        cmap3 = col.ListedColormap(cpool[::2], 'nice_spectral')
    else:
        cmap3 = col.ListedColormap(cpool[0:N], 'nice_spectral')
    cm.register_cmap(cmap=cmap3)
示例#46
0
def newgray():
    """ Modified version of Oranges."""
    oranges = cm.get_cmap("gray", 100)
    array = oranges(np.arange(100))
    array = array[40:]
    cmap = LinearSegmentedColormap.from_list("newgray", array)
    cm.register_cmap(name='newgray', cmap=cmap)
    array = array[::-1]
    cmap = LinearSegmentedColormap.from_list("newgray_r", array)
    cm.register_cmap(name='newgray_r', cmap=cmap)
    return
示例#47
0
def dep_erosion():
    """DEP Erosion ramp yelllow to brown (jump at 5T) `cool`"""
    cpool = [
        '#FFFF80', '#FCDD60', '#F7BE43', '#E69729', '#B35915', '#822507',
        '#00ffff', '#2ad5ff', '#55aaff', '#807fff', '#aa55ff', '#d52aff',
     ]
    cmap = mpcolors.ListedColormap(cpool, 'dep_erosion')
    cmap.set_over("#000000")
    cmap.set_under("#FFFFFF")
    cmap.set_bad("#FFFFFF")
    cm.register_cmap(cmap=cmap)
    return cmap
def add_cmap(name, cdict):
    """
    Adds a colormap to the colormaps available in yt for this session
    """
    yt_colormaps[name] = \
        cc.LinearSegmentedColormap(name,cdict,256)
    mcm.datad[name] = cdict
    mcm.__dict__[name] = cdict
    try: # API compatibility
        mcm.register_cmap(name, yt_colormaps[name])
    except AttributeError:
        pass
示例#49
0
def plotUsage(data, name='File Usage' ,outname = 'filestuff', limits = None, points=None, subtitle = None):
    '''plot the file layout data given a a list of MB transformed by the method
        in this file'''
    plt.figure()
    
    newData = []
    row = 0
    for i in data:
        if row % 2 == 0:
            newData.append(i)
        row = row + 1
    data = numpy.array(newData)
    # define the colormap
    clrMap = plt.cm.jet
    # extract all colors from the .jet map
    cmaplist = [clrMap(i) for i in xrange(clrMap.N)]
    # force the first color entry to be grey
    cmaplist[0] = (1.0,1.0,1.0,1.0)
# create the new map
    clrMap = clrMap.from_list('custommap', cmaplist, clrMap.N)
    cm.register_cmap(name='custommap', cmap=clrMap)
    #get axis
    maxy = len(data)
    maxx = pow(1,20) 
    plt.pcolormesh(data,vmin = 1, cmap='custommap')#, cmap = mcolor.colormap('gist_ncar'))
    plt.xlabel('Offset within Mb (kb)')
    plt.ylabel('Mb Offset in File')

    if len(name) > 100:
        plt.title(name, fontsize=8)
    else:
        plt.title(name, fontsize=10)
    plt.colorbar()

    if points != None:
        px = [i[0] for i in points]
        py = [i[1]/2 for i in points]
        plt.scatter(px,py, marker=(5,1), c='goldenrod')


    #fix the y labels
    spacing = int(maxy/10)
    locs = [y for y in xrange(0, maxy,spacing)]
    labs = [str(y) for y in locs]
    plt.yticks(locs,labs)
    plt.xlim(0,maxx)
    plt.ylim(0,maxy)

    
    locs = [256, 512, 789, 1024]
    labs = [str(x) for x in locs]
    plt.xticks(locs,labs)
    plt.savefig(outname+ '.png')
示例#50
0
def getColorMap():
    """
       This function returns the standard University of Tuebingen Colormap. 
    """    
    midBlue = np.array([165, 30, 55])/255
    lightBlue = np.array([210, 150, 0])/255
    steps = 200
    
    MAP = mcolors.LinearSegmentedColormap.from_list('Tuebingen', \
                    [midBlue, lightBlue, [1,1,1]],N = steps, gamma = 1.0) 
    cm.register_cmap(name = 'Tuebingen', cmap = MAP)
    return MAP
示例#51
0
def temp_style_file(name):
    """ A context manager for creating an empty style file in the expected path.
    """
    stylelib_path = USER_LIBRARY_PATHS[0]
    if not os.path.exists(stylelib_path):
        os.makedirs(stylelib_path)
    srcname = os.path.abspath(os.path.join(os.path.dirname(__file__),name))
    dstname = os.path.join(stylelib_path, os.path.basename(name))
    if not os.path.exists(srcname):
        raise RuntimeError('Cannot use file at "' + srcname + '". This file does not exist.')
    if os.path.exists(dstname):
        #raise RuntimeError('Cannot create a temporary file at "' + dstname + '". This file exists already.')
        warnings.warn('Overwriting the temporary file at "' + dstname + '".')
    
    #with open(filename, 'w'):
    #    pass
    
    shutil.copy2(srcname, dstname)
    
    
    rgb = [
      (  0./255. ,   0./255. ,   0./255.),     
      (  0./255. , 102./255. ,  51./255.),
      #(114./255. , 121./255. , 126./255.),
      ( 91./255. , 172./255. ,  38./255.),
      (217./255. , 220./255. , 222./255.),
      (255./255. , 255./255. , 255./255.)
      ]

    # create map and register it together with reversed colours
    maps = []
    maps.append(LinearSegmentedColormap.from_list('IPU'  , rgb))
    maps.append(LinearSegmentedColormap.from_list('IPU_r', rgb[::-1]))

    for cmap in maps:
        mplcm.register_cmap(cmap=cmap)
        #self._color_maps[cmap.name] = cmap
    
    yield
    os.remove(dstname)



#print('# styles available:', len(plt.style.available))
#
#with temp_style_file('dummy.mplstyle'):
#    print('# before reload:', len(plt.style.available))
#
#    plt.style.reload_library()
#    print('# after reload:', len(plt.style.available))
示例#52
0
def maue(N=-1):
    """ Pretty color ramp Dr Ryan Maue uses """
    cpool = ["#e6e6e6", "#d2d2d2", "#bcbcbc", "#969696", "#646464",
"#1464d2", "#1e6eeb", "#2882f0", "#3c96f5", "#50a5f5", "#78b9fa", 
           "#96d2fa", "#b4f0fa", "#e1ffff",
"#0fa00f", "#1eb41e", "#37d23c", "#50f050", "#78f573", "#96f58c", 
           "#b4faaa", "#c8ffbe",
"#ffe878", "#ffc03c", "#ffa000", "#ff6000", "#ff3200", "#e11400", "#c00000", 
           "#a50000", "#643c32",
"#785046", "#8c645a", "#b48c82", "#e1beb4", "#f0dcd2", "#ffc8c8", "#f5a0a0", 
           "#f5a0a0", "#e16464", "#c83c3c"]
    cmap3 = mpcolors.ListedColormap(cpool[0:N], 'maue', N=N)
    mpcm.register_cmap(cmap=cmap3)
    return cmap3
示例#53
0
def registerDAEROcmap():
    """standardized colormap from A-AERO projects (purple=0.3 to red=500)"""
    CMY = np.array([
        [127, 255, 31], [111, 255, 47], [95, 255, 63], [79, 255, 79],
        [63, 255, 95], [47, 255, 111], [31, 255, 127], [16, 255, 159],
        [0, 223, 159], [0, 191, 159], [0, 159, 207], [0, 127, 175],
        [0, 95, 175], [0, 63, 175], [0, 47, 175], [0, 31, 191], [0, 0, 255],
        [0, 0, 159], [15, 0, 127], [47, 0, 143], [79, 0, 143], [111, 0, 143],
        [143, 0, 127], [159, 31, 63], [175, 47, 31], [207, 63, 0],
        [223, 111, 0], [231, 135, 0], [239, 159, 0], [255, 191, 47],
        [239, 199, 63], [223, 207, 79], [207, 239, 111]], dtype=float)
    RGB = 1.0 - CMY/255
    daero = LinearSegmentedColormap.from_list('D-AERO', RGB)
    register_cmap(name='daero', cmap=daero)
    return daero
示例#54
0
文件: colors.py 项目: gmatteo/wxmplot
def register_custom_colormaps():
    """
    registers custom color maps
    """
    makemap = LinearSegmentedColormap.from_list
    for name, val in custom_colormap_data.items():
        cm1 = np.array(val).transpose().astype('f8')/256.0
        cm2 = cm1[::-1]
        nam1 = name
        nam2 = '%s_r' % name
        register_cmap(name=nam1, cmap=makemap(nam1, cm1, 256), lut=256)
        register_cmap(name=nam2, cmap=makemap(nam2, cm2, 256), lut=256)

    return ('stdgamma', 'red_heat', 'green_heat', 'blue_heat',
            'red', 'green', 'blue')
示例#55
0
def whitebluegreenyellowred():
    ''' Rip off NCL's WhiteBlueGreenYellowRed '''
    cpool = ['#cfedfb', '#cdecfb', '#caebfb', '#c7eafa', '#c5e9fa', '#c2e8fa',
             '#bfe7fa', '#bde6fa', '#bae5f9', '#b7e4f9', '#b5e3f9', '#b2e2f9',
             '#b0e1f9', '#ade0f8', '#aadff8', '#a8def8', '#a5ddf8', '#a2dcf7',
             '#9ddaf7', '#9bd8f6', '#98d6f5', '#96d4f3', '#94d2f2', '#92d0f1',
             '#8fcef0', '#8dccee', '#8bcaed', '#88c8ec', '#86c5eb', '#84c3ea',
             '#81c1e8', '#7fbfe7', '#7dbde6', '#7bbbe5', '#78b9e4', '#76b7e2',
             '#74b5e1', '#71b3e0', '#6fb1df', '#6dafdd', '#6aaddc', '#68abdb',
             '#66a9da', '#64a7d9', '#61a5d7', '#5fa3d6', '#5da0d5', '#5a9ed4',
             '#589cd3', '#569ad1', '#5398d0', '#5196cf', '#4f94ce', '#4d92cc',
             '#488eca', '#488fc6', '#4890c3', '#4891bf', '#4892bc', '#4893b8',
             '#4894b5', '#4895b1', '#4896ad', '#4897aa', '#4899a6', '#489aa3',
             '#489b9f', '#489c9c', '#489d98', '#489e94', '#489f91', '#48a08d',
             '#48a18a', '#49a286', '#49a383', '#49a47f', '#49a57c', '#49a678',
             '#49a774', '#49a871', '#49a96d', '#49aa6a', '#49ac66', '#49ad63',
             '#49ae5f', '#49af5b', '#49b058', '#49b154', '#49b251', '#49b34d',
             '#49b546', '#4eb647', '#53b847', '#57b948', '#5cbb48', '#61bc49',
             '#66bd4a', '#6abf4a', '#6fc04b', '#74c14b', '#79c34c', '#7ec44d',
             '#82c64d', '#87c74e', '#8cc84e', '#91ca4f', '#96cb50', '#9acc50',
             '#9fce51', '#a4cf51', '#a9d152', '#add252', '#b2d353', '#b7d554',
             '#bcd654', '#c1d755', '#c5d955', '#cada56', '#cfdc57', '#d4dd57',
             '#d9de58', '#dde058', '#e2e159', '#e7e25a', '#ece45a', '#f0e55b',
             '#f5e75b', '#fae85c', '#fae55b', '#fae159', '#fade58', '#f9da56',
             '#f9d755', '#f9d454', '#f9d052', '#f9cd51', '#f9c950', '#f9c64e',
             '#f9c34d', '#f8bf4b', '#f8bc4a', '#f8b849', '#f8b547', '#f8b246',
             '#f8ae45', '#f8ab43', '#f7a742', '#f7a440', '#f7a03f', '#f79d3e',
             '#f79a3c', '#f7963b', '#f7933a', '#f68f38', '#f68c37', '#f68935',
             '#f68534', '#f68233', '#f67e31', '#f67b30', '#f6782f', '#f5742d',
             '#f5712c', '#f56a29', '#f46829', '#f36629', '#f26429', '#f16229',
             '#f06029', '#ef5e29', '#ef5c29', '#ee5a29', '#ed5829', '#ec5629',
             '#eb5429', '#ea5229', '#e95029', '#e84e29', '#e74c29', '#e64a29',
             '#e54829', '#e44629', '#e44328', '#e34128', '#e23f28', '#e13d28',
             '#e03b28', '#df3928', '#de3728', '#dd3528', '#dc3328', '#db3128',
             '#da2f28', '#d92d28', '#d92b28', '#d82928', '#d72728', '#d62528',
             '#d52328', '#d31f28', '#d11f28', '#cf1e27', '#ce1e27', '#cc1e26',
             '#ca1e26', '#c81d26', '#c71d25', '#c51d25', '#c31d24', '#c11c24',
             '#c01c24', '#be1c23', '#bc1b23', '#ba1b22', '#b91b22', '#b71b22',
             '#b51a21', '#b31a21', '#b21a20', '#b01a20', '#ae191f', '#ac191f',
             '#ab191f', '#a9191e', '#a7181e', '#a5181d', '#a4181d', '#a2171d',
             '#a0171c', '#9e171c', '#9d171b', '#9b161b', '#99161b', '#97161a',
             '#96161a', '#921519']
    cmap3 = mpcolors.ListedColormap(cpool, 'whitebluegreenyellowred')
    cmap3.set_over("#000000")
    cmap3.set_under("#FFFFFF")
    cmap3.set_bad("#FFFFFF")
    cm.register_cmap(cmap=cmap3)
    return cmap3
示例#56
0
def cubelaw():
    """ Definition of the Cube Law Rainbow colormap"""
    grb = np.loadtxt(os.path.join(tables_dir, "cube1.csv"))
    r = np.linspace(0., 1., 256)
    cdict = {"red" : tuple(zip(r, grb[:,0], grb[:,0])), 
             "green" : tuple(zip(r, grb[:,1], grb[:,1])),
             "blue" : tuple(zip(r, grb[:,2], grb[:,2]))}
    cmap = LinearSegmentedColormap("cubelaw", cdict, 256)
    cm.register_cmap(name='cubelaw', cmap=cmap)
    grb = grb[::-1]
    cdict = {"red" : tuple(zip(r, grb[:,0], grb[:,0])), 
             "green" : tuple(zip(r, grb[:,1], grb[:,1])),
             "blue" : tuple(zip(r, grb[:,2], grb[:,2]))}
    cmap = LinearSegmentedColormap("cubelaw_r", cdict, 256)
    cm.register_cmap(name='cubelaw_r', cmap=cmap)
    return
示例#57
0
文件: color_maps.py 项目: sbs87/qpcr
def register_own_cmaps():
    """define two example colormaps as segmented lists and register them"""
    # a good guide for choosing colors is provided at
    # http://geography.uoregon.edu/datagraphics/color_scales.htm
    #
    # example 1:
    # create own colormap from purple, blue, green, orange to red
    # cdict contains a tuple structure for 'red', 'green', and 'blue'.
    # Each color has a list of (x,y0,y1) tuples, where
    # x defines the "index" in the colormap (range 0..1), y0 is the
    # color value (0..1) left of x, and y1 the color value right of x.
    # The LinearSegmentedColormap method will linearly interpolate between
    # (x[i],y1) and (x[i+1],y0)
    # The gamma value denotes a "gamma curve" value which adjusts the brightness
    # at the bottom and top of the colormap. According to matlab documentation
    # this means:
    # colormap values are modified as c^gamma, where gamma is (1-beta) for
    # beta>0 and 1/(1+beta) for beta<=0
    cdict = {'red': ((0.0, 0.0, 0.0),
                     (0.3, 0.5, 0.5),
                     (0.6, 0.7, 0.7),
                     (0.9, 0.8, 0.8),
                     (1.0, 0.8, 0.8)),
         'green': ((0.0, 0.0, 0.0),
                   (0.3, 0.8, 0.8),
                   (0.6, 0.7, 0.7),
                   (0.9, 0.0, 0.0),
                   (1.0, 0.7, 0.7)),
         'blue': ((0.0, 1.0, 1.0),
                  (0.3, 1.0, 1.0),
                  (0.6, 0.0, 0.0),
                  (0.9, 0.0, 0.0), 
                  (1.0, 1.0, 1.0))}
    cmap1 = col.LinearSegmentedColormap('my_colormap',cdict,N=256,gamma=0.75)
    cm.register_cmap(name='own1', cmap=cmap1)

    # example 2: use the "fromList() method
    startcolor = '#586323'  # a dark olive 
    midcolor = '#fcffc9'    # a bright yellow
    endcolor = '#bd2309'    # medium dark red
    cmap2 = col.LinearSegmentedColormap.from_list('own2',[startcolor,midcolor,endcolor])
    # extra arguments are N=256, gamma=1.0
    cm.register_cmap(cmap=cmap2)
    # we can skip name here as it was already defined 
    return cmap2
示例#58
0
def discrete_cmap(N=10):
  """create a c colormap with N (N<12) discrete colors and register it"""
   import matplotlib
   import matplotlib.colors as col
   import matplotlib.cm as cm
   import matplotlib.pyplot as plt
   import numpy as np

   # define individual colours as hex values
   #clog=['#0000FF','#0099FF','#00FFFF','#66FF00','#CCFF00',
   #	 '#FFFF00','#FFCC00','#FF9900','#FF3300','#CC0000',
   #	 '#CC00CC','#FFCCFF']
   
   clog=['#CC00CC','#CC00CC','#CC00CC','#CC00CC','#CC00CC',
   	'#CC00CC','#CC00CC','#CC00CC','#CC00CC','#CC00CC',
	'#CC00CC','#CC00CC','#CC00CC','#CC00CC','#CC00CC']
   cmap3=col.ListedColormap(clog[0:N],'indexed')
   cm.register_cmap(cmap=cmap3)
示例#59
0
def nwsprecip():
    """A color ramp used by NWS on NTP plots

    Changes
     - modified the reds a bit to provide a larger gradient
     - added two light brown colors at the low end to allow for more levels
     - removed perhaps a bad orange color and remove top white color
    """
    cpool = ["#cbcb97", "#989865",
             "#00ebe7", "#00a0f5", "#000df5", "#00ff00", "#00c600",
             "#008e00", "#fef700", "#e5bc00", "#ff8500", "#ff0000",
             "#af0000", "#640000", "#ff00fe", "#a152bc"]
    cmap = mpcolors.ListedColormap(cpool, 'nwsprecip')
    cmap.set_over('#FFFFFF')
    cmap.set_under('#FFFFFF')
    cmap.set_bad("#FFFFFF")
    cm.register_cmap(cmap=cmap)
    return cmap
示例#60
0
文件: mplib.py 项目: jowr/jopy
    def _register_color_maps(self):
        BaseStyle._register_color_maps(self)
        rgb = [
          ( 25./255. ,  13./255. ,  25./255.),
          (  0./255. ,  51./255. , 102./255.),     
          #(205./255. ,  51./255. ,  51./255.),
          (  0./255. , 109./255. , 148./255.),
          (127./255. , 186./255. ,  50./255.),
          (255./255. , 255./255. , 255./255.)]

        # create map and register it together with reversed colours
        maps = []
        maps.append(LinearSegmentedColormap.from_list('VDG'  , rgb))
        maps.append(LinearSegmentedColormap.from_list('VDG_r', rgb[::-1]))
    
        for cmap in maps:
            mplcm.register_cmap(cmap=cmap)
            self._color_maps[cmap.name] = cmap