예제 #1
0
def register_colour_maps():
    cdict = {'red':   ((0.0,  0.0, 0.0),
                       (0.0,  0.0, 0.0),
                       (1.0,  1.0, 1.0)),
                       
         'green': ((0.0,  0.0, 0.0),
                   (0.0,  0.0, 0.0),
                   (1.0,  1.0, 1.0)),
                   
         'blue':  ((0.0,  0.0, 0.0),
                   (0.0,  0.0, 0.0),
                   (1.0,  1.0, 1.0))}
    
    plt.register_cmap(name='GreyIntensity', data=cdict)
    
    cdict2 = {'red': ((0.0, 0.0, 0.0),
                 (0.5, 1.0, 0.7),
                 (1.0, 1.0, 1.0)),
         'green': ((0.0, 0.0, 0.0),
                   (0.5, 1.0, 0.0),
                   (1.0, 1.0, 1.0)),
         'blue': ((0.0, 0.0, 0.0),
                  (0.5, 1.0, 0.0),
                  (1.0, 0.5, 1.0))}
    
    plt.register_cmap(name='RedSplit', data=cdict2)
예제 #2
0
def shifted_cmap(cmap,vmin,vmax,start=0.0,stop=1.0,name='new_cmap'):
	""" This code comes primarily from an answer to a question on stackoverflow
	url as of 2016-06-30 was http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib
	and the answer / code was from Paul H. http://stackoverflow.com/users/1552748/paul-h
	"""
	mid = 1.0-vmax/(vmax + np.absolute(vmin))
	colors = {
	'red': [],
	'green': [],
	'blue': [],
	'alpha': []
	}
	reg_index = np.linspace(start,stop,257)
	shift_index = np.hstack([
        np.linspace(0.0, mid, 128, endpoint=False), 
        np.linspace(mid, 1.0, 129, endpoint=True)
    ])

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

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

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

	return newcmap
예제 #3
0
def _set_colors():
    HighRGB = np.array([26, 152, 80]) / 255.
    MediumRGB = np.array([255, 255, 191]) / 255.
    LowRGB = np.array([0, 0, 0]) / 255.
    cdict = _set_cdict(HighRGB, MediumRGB, LowRGB)
    plt.register_cmap(name='PyMKS', data=cdict)
    plt.set_cmap('PyMKS')
예제 #4
0
파일: cmap.py 프로젝트: syrte/handy
def make_rainbow(a=0.75, b=0.2, name='custom_rainbow', register=False):
    """
    Use a=0.7, b=0.2 for a darker end.

    when 0.5<=a<=1.5, should have b >= (a-0.5)/2 or 0 <= b <= (a-1)/3
    when 0<=a<=0.5, should have b >= (0.5-a)/2 or 0<= b<= -a/3
    to assert the monoique

    To show the parameter dependencies interactively in notebook
    ```
    %matplotlib inline
    from ipywidgets import interact
    def func(a=0.75, b=0.2):
        cmap = gene_rainbow(a=a, b=b)
        show_cmap(cmap)
    interact(func, a=(0, 1, 0.05), b=(0.1, 0.5, 0.05))
    ```
    """
    def gfunc(a, b, c=1):
        def func(x):
            return c * np.exp(-0.5 * (x - a)**2 / b**2)
        return func

    cdict = {"red": gfunc(a, b),
             "green": gfunc(0.5, b),
             "blue": gfunc(1 - a, b)
             }
    cmap = mpl.colors.LinearSegmentedColormap(name, cdict)
    if register:
        plt.register_cmap(cmap=cmap)
        plt.rc('image', cmap=cmap.name)
    return cmap
예제 #5
0
def custom_cmap(_sample, _reverse=False):
    midpoint  = .5
    from scipy.ndimage import imread
    im = imread(_sample, mode='RGBA')
    im = im[10:-10,20:-20,:]
    im = im/im.max()
    if _reverse:
        im = np.rot90(im,2)
    nx,ny,nz = im.shape
    my_index = np.linspace(0,ny,257, endpoint=False)
    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }
    shift_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False),
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])
    for i, si in zip(my_index, shift_index):
        i = int(i)
        r,g,b,a = (im[0,i,0],
                   im[0,i,1],
                   im[0,i,2],
                   im[0,i,3])
        cdict['red'].append((si, r, r))
        cdict['green'].append((si, g, g))
        cdict['blue'].append((si, b, b))
        cdict['alpha'].append((si, a, a))
    mycmap = matplotlib.colors.LinearSegmentedColormap('custom', cdict)
    plt.register_cmap(cmap=mycmap)
    return mycmap
예제 #6
0
파일: sound.py 프로젝트: choldgraf/LaSP
def spec_colormap():
# Makes the colormap that we like for spectrograms

    cmap = np.zeros((64,3))
    cmap[0,2] = 1.0

    for ib in range(21):
        cmap[ib+1,0] = (31.0+ib*(12.0/20.0))/60.0
        cmap[ib+1,1] = (ib+1.0)/21.0
        cmap[ib+1,2] = 1.0

    for ig in range(21):
        cmap[ig+ib+1,0] = (21.0-(ig)*(12.0/20.0))/60.0
        cmap[ig+ib+1,1] = 1.0
        cmap[ig+ib+1,2] = 0.5+(ig)*(0.3/20.0)

    for ir in range(21):
        cmap[ir+ig+ib+1,0] = (8.0-(ir)*(7.0/20.0))/60.0
        cmap[ir+ig+ib+1,1] = 0.5 + (ir)*(0.5/20.0)
        cmap[ir+ig+ib+1,2] = 1

    for ic in range(64):
        (cmap[ic,0], cmap[ic,1], cmap[ic,2]) = colorsys.hsv_to_rgb(cmap[ic,0], cmap[ic,1], cmap[ic,2])
    
    spec_cmap = pltcolors.ListedColormap(cmap, name=u'SpectroColorMap', N=64)
    plt.register_cmap(cmap=spec_cmap)
예제 #7
0
파일: stgrism.py 프로젝트: gbrammer/wfc3
def compare_spectra():
    import mywfc3.stgrism as st
    import unicorn
    
    ### Fancy colors
    import seaborn as sns
    import matplotlib.pyplot as plt
    cmap = sns.cubehelix_palette(as_cmap=True, light=0.95, start=0.5, hue=0.4, rot=-0.7, reverse=True)
    cmap.name = 'sns_rot'
    plt.register_cmap(cmap=cmap)
    sns.set_style("ticks", {"ytick.major.size":3, "xtick.major.size":3})
    plt.set_cmap('sns_rot')
    #plt.gray()
    
    fig = st.compare_methods(x0=787, y0=712, v=np.array([-1.5,4])*0.6, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.02)
    #fig.tight_layout()
    unicorn.plotting.savefig(fig, '/tmp/compare_model_star.pdf', dpi=300)

    fig = st.compare_methods(x0=485, y0=332, v=np.array([-1.5,4])*0.2, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.1)
    unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy.pdf', dpi=300)

    fig = st.compare_methods(x0=286, y0=408, v=np.array([-1.5,4])*0.08, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.1)
    unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy2.pdf', dpi=300)

    fig = st.compare_methods(x0=922, y0=564, v=np.array([-1.5,4])*0.2, NX=180, NY=40, direct_off=100, final=True, mask_lim = 0.15)
    unicorn.plotting.savefig(fig, '/tmp/compare_model_galaxy3.pdf', dpi=300)
예제 #8
0
def main():
    plt.register_cmap(name='viridis', cmap=cmaps.viridis)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = np.linspace(0.1, 20, num=50)
    Y = np.linspace(0.1, 20, num=50)
    Z = np.array([0.]*X.shape[0]*Y.shape[0])
    Z.shape = (X.shape[0], Y.shape[0])
    for i in range(X.shape[0]):
        for j in range(Y.shape[0]):
            he = hyperexp(0.5, X[i], Y[j])
            Z[i][j] = he.CoV()

    X, Y = np.meshgrid(X, Y)
    plt.xlabel('lambda1')
    plt.ylabel('lambda2')
    ax.set_zlabel('CoV')
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cmaps.viridis,
                           linewidth=0, antialiased=False, vmin=0., vmax=6)
    ax.set_zlim(0, 6)
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    fig.colorbar(surf, shrink=0.5, aspect=5)

    plt.show()
    return
예제 #9
0
파일: o2py.py 프로젝트: zyh329/o2scl
 def myblues(self):
     cdict={'red': ((0.0,1.0,1.0),(1.0,0.0,0.0)),
            'green': ((0.0,1.0,1.0),(1.0,0.0,0.0)),
            'blue': ((0.0,1.0,1.0),(1.0,1.0,1.0))}
     myblues=LinearSegmentedColormap('MyBlues',cdict)
     plot.register_cmap(cmap=myblues)
     self.cmap='MyBlues'
예제 #10
0
def remappedColorMap(cmap, data=False, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
	'''
	Function to offset the median value of a colormap, and scale the
	remaining color range. Useful for data with a negative minimum and
	positive maximum where you want the middle of the colormap's dynamic
	range to be at zero.

	Input
	-----
	cmap : The matplotlib colormap to be altered
	data: You can provide your data as a numpy array, and the following
		operations will be computed automatically for you.
	start : Offset from lowest point in the colormap's range.
		Defaults to 0.0 (no lower ofset). Should be between
		0.0 and 0.5; if your dataset vmax <= abs(vmin) you should leave 
		this at 0.0, otherwise to (vmax-abs(vmin))/(2*vmax) 
	midpoint : The new center of the colormap. Defaults to 
		0.5 (no shift). Should be between 0.0 and 1.0; usually the
		optimal value is abs(vmin)/(vmax+abs(vmin)) 
	stop : Offset from highets point in the colormap's range.
		Defaults to 1.0 (no upper ofset). Should be between
		0.5 and 1.0; if your dataset vmax >= abs(vmin) you should leave 
		this at 1.0, otherwise to (abs(vmin)-vmax)/(2*abs(vmin)) 
	'''
    
	if isinstance(data, np.ndarray):
		start, midpoint, stop = auto_remap(data)
    
    	cdict = {
    		'red': [],
    		'green': [],
    		'blue': [],
    		'alpha': []
    	}

    	# regular index to compute the colors
    	reg_index = np.hstack([
    			np.linspace(start, 0.5, 128, endpoint=False), 
    			np.linspace(0.5, stop, 129)
    	])

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

    	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
예제 #11
0
파일: anm_plot.py 프로젝트: mjanusz/sdepy
def make_subplot(options, ax, dplot, slicearg, data, pars, xvar, yvar, xidx, yidx, a, b):
    sc = a / (a+b) / 0.5
    sc2 = b / (a+b) / 0.5

    anm = {
        'red': [
            (0., 0.0, 0.0),
            (sc*0.5, 1.0, 1.0),
            (sc*0.5 + (0.817460-0.5)*sc2, 1.0, 1.0),
            (1.0, 0.8, 0.8)],

        'green': [
            (0., 0.0, 0.0),
            (sc*0.4, 1.0, 1.0),
            (sc*0.5, 1.0, 1.0),
            (sc*0.5 + (0.626984-0.5)*sc2, 1.0, 1.0),
            (sc*0.5 + (0.817460-0.5)*sc2, 0.6, 0.6),
            (1.0, 0.0, 0.0)],

        'blue': [
            (0.0, 0.4, 0.4),
            (sc*0.25, 1.0, 1.0),
            (sc*0.5, 1.0, 1.0),
            (sc*0.5 + (0.626984-0.5)*sc2, 0., 0.),
            (1.0, 0.0, 0.0)]
        }

    if sc == 0.0:
        for k in anm.iterkeys():
            anm[k] = anm[k][1:]
    # Fix color scale if only positive values are present.
    elif a < 0.001:
        for k in anm.iterkeys():
            anm[k][0] = (0., 1.0, 1.0)

    if b < 0.001:
        anm['red'] = anm['red'][0:1] + [(1, 1, 1)]
        anm['green'] = anm['green'][0:2] + [(1, 1, 1)]
        anm['blue'] = anm['blue'][0:2] + [(1, 1 ,1)]

    anm_cmap = LinearSegmentedColormap('ANM', anm)
    plt.register_cmap(cmap=anm_cmap)

    aspect = ((data[pars[xidx]][-1] - data[pars[xidx]][0]) /
              (data[pars[yidx]][-1] - data[pars[yidx]][0])) / options.panel_aspect

    im = ax.imshow(dplot[slicearg],
           extent=(data[pars[xidx]][0], data[pars[xidx]][-1],
                   data[pars[yidx]][0], data[pars[yidx]][-1]),
           aspect=aspect,
           interpolation='bilinear',
#           interpolation='nearest',
           vmin = -a,
           vmax = b,
           cmap = anm_cmap,
           origin='lower')

    return im
예제 #12
0
def lin_cmap_gen(incolgs, regname, fractions = None):
    '''
    Generates a color map with the given color list (incolgs).
    Accepts a list of color words (defined by the color.gs script:
        http://kodama.fubuki.info/wiki/wiki.cgi/GrADS/script/color.gs?lang=en)
    or a list of (r,g,b) values. The r,g,b values can be either 0<=x<=1 or 0<=x<=255

    input:
        incolgs: Input color map request
        regname: Name for matplotlib to register color map.
        fractions: Fraction for each color to take up- these values must
                   add to 1. If not, a ValueException is raised. (NOT YET IMPLEMENTED)

    returns:
        a LinearSegmentedColormap containing your colors.
    '''
    collists = incolgs
    reds = list()
    greens = list()
    blues = list()
    reds_prep = list()
    greens_prep = list()
    blues_prep = list()

    if fractions != None:
        raise NotImplementedError("Fractional colors are not yet implemented.")

    for i, color in enumerate(collists):
        try:
            if (color[0] >= 0 and color[0] <= 255 and
                color[1] >= 0 and color[1] <= 255 and
                color[2] >= 0 and color[2] <= 255):

                rgb = convert_color(color)
            else:
                raise ValueError("Colors need to be between 0 and 255")

        except TypeError:
            rgb = get_rgb(color)

        reds.append(rgb[0])
        greens.append(rgb[1])
        blues.append(rgb[2])
    for i in range(len(reds)):
        rp = ((float(i)/(len(reds)-1)))
        drp = ((1.0/(len(reds)-1)))
        if rp+drp >=1:
            drp = 0
        reds_prep.append((rp, reds[i],reds[i]))
        blues_prep.append((rp, blues[i], blues[i]))
        greens_prep.append((rp, greens[i], greens[i]))

    cdict = {'red': tuple(reds_prep), 'blue': tuple(blues_prep), 
             'green': tuple(greens_prep)}
    #print(cdict)
    ucmap = LinearSegmentedColormap(regname, cdict)
    plt.register_cmap(cmap=ucmap)
    return ucmap
예제 #13
0
파일: utils.py 프로젝트: jGaboardi/pysal
def shift_colormap(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

    Parameters
    ----------
    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.
    
    Returns
    -------
    new_cmap : A new colormap that has been shifted. 
    '''
    
    import matplotlib as mpl
    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))

    new_cmap = mpl.colors.LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=new_cmap)

    return new_cmap
예제 #14
0
파일: viz.py 프로젝트: mohseniaref/altimpy
def shift_cmap(cmap, start=0, midpoint=0.5, stop=1, name='shiftedcmap'):
    '''Offset the median value of a colormap.
    
    And scale the remaining color range. Useful for data with a negative
    minimum and positive maximum where 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 0.5; if your dataset mean is negative you should leave 
          this at 0.0, otherwise to (vmax-abs(vmin))/(2*vmax) 
      midpoint : The new center of the colormap. Defaults to 
          0.5 (no shift). Should be between 0.0 and 1.0; usually the
          optimal value is abs(vmin)/(vmax+abs(vmin)) 
      stop : Offset from highets point in the colormap's range.
          Defaults to 1.0 (no upper ofset). Should be between
          0.5 and 1.0; if your dataset mean is positive you should leave 
          this at 1.0, otherwise to (abs(vmin)-vmax)/(2*abs(vmin)) 

    Credits
    -------
    Paul H (initial version)
    Horea Christian (additions/modifications)
    Fernando Paolo (additions/modifications)

    TODO
    ----
    Set 'start' and 'stop' dynamically when negative/positive bounds.

    '''
    # if array given, find optimal value to center new cmap
    if np.ndim(midpoint) != 0:
        midpoint = np.asarray(midpoint)[~np.isnan(midpoint)]
        midpoint = abs(midpoint.min()) / float(abs(midpoint.max()) + \
                                               abs(midpoint.min())) 
    # regular index to compute the colors
    reg_index = np.hstack([
        np.linspace(start, 0.5, 128, endpoint=False), 
        np.linspace(0.5, stop, 129, endpoint=True)
    ])
    # shifted index to match the midpoint of the data
    new_index = np.hstack([
        np.linspace(0.0, midpoint, 128, endpoint=False), 
        np.linspace(midpoint, 1.0, 129, endpoint=True)
    ])
    cdict = {'red': [], 'green': [], 'blue': [], 'alpha': []}
    for ri, si in zip(reg_index, new_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 = mpl.colors.LinearSegmentedColormap(name, cdict, 256)
    plt.register_cmap(cmap=newcmap)
    return newcmap
예제 #15
0
파일: tools.py 프로젝트: bodagetta/pymks
def _set_colors():
    """
    Helper function used to set the color map.
    """
    HighRGB = np.array([26, 152, 80]) / 255.
    MediumRGB = np.array([255, 255, 191]) / 255.
    LowRGB = np.array([0, 0, 0]) / 255.
    cdict = _set_cdict(HighRGB, MediumRGB, LowRGB)
    plt.register_cmap(name='PyMKS', data=cdict)
    plt.set_cmap('PyMKS')
예제 #16
0
def wrappedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
    '''
    The idea here is that after your midpoint, you start going back down to
    zero. Useful for angles.

    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.

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

    # regular index to compute the colors
    reg_index = np.linspace(start, stop, 257)
    reg_index = np.hstack([
        np.linspace(start, stop, 128, endpoint=False), 
        np.linspace(stop, start, 129, endpoint=True)
    ])


    # 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 = LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap
예제 #17
0
파일: utils.py 프로젝트: Venki-Kavuri/bopy
def showbluered(data):
    plt.register_cmap(name='BlueRed3', data=cdict3)
    plt.clf()
    fig = plt.figure()
    ax = plt.subplot(111)
    mx = np.abs(np.max(data))
    mn = np.abs(np.min(data)) 
    vmax = np.max((mx, mn))
    ax.imshow(data, interpolation='nearest', vmax=vmax, vmin=-vmax)
    ax.set_cmap('BlueRed3')
    plt.show()
예제 #18
0
파일: propP2PPlot.py 프로젝트: G4FKH/proppy
    def do_polar_bar_plot(self, plot_type, dpi=150, cmap='jet', file_format='png'):
        '''
        A doodle to look at different ways of presenting data.
        '''
        try:
            muf_data, im_data, global_params = self.r533.get_p2p_plot_data(plot_type)
        except LookupError:
            return
        #points, plot_type, lons, lats, num_pts_lon, num_pts_lat, global_params, params = dataset
        #plot_dt, ssn, freq = params
        # EDIT THE LINE BELOW TO MODIFY COLOURS IN THE COLORMAP
        plt.clf() #Clear any existing plot data, specifically nightshade

        plt.register_cmap(name='PlotlyAlt', cmap=PlotlyAlt)

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='polar')

        palette=plt.get_cmap(cmap)

        rad_hour = (2 * np.pi) / 24.0
        start_theta = (np.pi / 2.0) + rad_hour/2.0
        theta = np.arange(start_theta, (-2.0*np.pi) + (np.pi/2.0) + (rad_hour/2.0), -rad_hour)
        radii = [0.5, 0.8, .6, .3, .2, .4, .8, 1.0 ,0.5, 0.8, .6, .3, .2, .4, .8, 1.0 ,0.5, 0.8, .6, .3, .2, .4, .8, 1.0]
        radii = []
        indexes = []
        for hour in range(0,24):
            idx = np.argmax(im_data[hour,:])
            radii.append(im_data[hour,idx])
            indexes.append(idx)
        bars = ax.bar(theta, radii, width=-rad_hour, bottom=0.0)
        for r, bar, idx in zip(radii, bars, indexes):
            c = palette(int((256/28)*idx))
            bar.set_facecolor(c)
            bar.set_edgecolor(c)
            bar.set_alpha(0.75)


        main_title = "{:s}".format(global_params.title)
        tx_ant_str = "{:s} ({:.1f}dB)".format(global_params.tx_ant_type, global_params.tx_ant_gain)

        #pythonProp subtitle
        #sub_title = "{:s} - {:s} - SSN:{:.1f} - {:.3f}MHz - {:s} - {:.0f}W".format(plot_params['title'], plot_dt.strftime(ds_fmt_str), ssn, float(freq), tx_ant_str, global_params.tx_pwr)
        #RSGB subtitle
        sub_title = "{:s} {:s} {:.0f}W".format(self.plot_params['title'], tx_ant_str, global_params.tx_pwr)

        #plt.figtext(0.5, 0.8, main_title, fontsize=18, ha='center')
        #plt.figtext(0.5, 0.76,sub_title,fontsize=10, fontstyle='normal', ha='center')

        #todo if we're using voacap files we can include the year in the filename
        #plot_fn = "p2p_{:s}_{:s}_{:s}.{:s}".format(plot_type, "d".join(str(freq).split('.')), file_format)
        plot_fn = 'test.svg'
        print ("Saving file ", plot_fn)
        plt.savefig(plot_fn, dpi=float(dpi), bbox_inches='tight')
예제 #19
0
 def remappedColorMap(self, cmap, start=0, midpoint=0.5, stop=1.0,
     name='shiftedcmap'):
     '''
     Function to offset the median value of a colormap, and scale the
     remaining color range. Useful for data with a negative minimum and
     positive maximum where 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 0.5; if your dataset mean is negative you should leave
     this at 0.0, otherwise to (vmax-abs(vmin))/(2*vmax)
     midpoint : The new center of the colormap. Defaults to
     0.5 (no shift). Should be between 0.0 and 1.0; usually the
     optimal value is abs(vmin)/(vmax+abs(vmin))
     stop : Offset from highets point in the colormap's range.
     Defaults to 1.0 (no upper ofset). Should be between
     0.5 and 1.0; if your dataset mean is positive you should leave
     this at 1.0, otherwise to (abs(vmin)-vmax)/(2*abs(vmin))
     http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib
     '''
     cdict = {
         'red': [],
         'green': [],
         'blue': [],
         'alpha': []
     }
 
     # regular index to compute the colors
     reg_index = np.hstack([
         np.linspace(start, 0.5, 128, endpoint=False),
         np.linspace(0.5, stop, 129)
     ])
 
     # shifted index to match the data
     shift_index = np.hstack([
         np.linspace(0.0, midpoint, 128, endpoint=False),
         np.linspace(midpoint, 1.0, 129)
     ])
         
     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 = mpl.colors.LinearSegmentedColormap(name, cdict)
     plt.register_cmap(cmap=newcmap)
 
     return newcmap
예제 #20
0
파일: graphics.py 프로젝트: jobar8/graphics
def load_cmap(name='geosoft'):
    """
    Create and register a color map. The name must be selected from the 
    colormaps available in the local colors module.
    """
    try:
        cmList = colors.datad[name]
        new_cm = mcolors.LinearSegmentedColormap.from_list(name, cmList)
        plt.register_cmap(cmap=new_cm)
        return new_cm
    except:
        raise ValueError('Colormap {} has not been recognised'.format(name))
예제 #21
0
파일: HiCPlot.py 프로젝트: Phlya/hicplotlib
 def apply_cmap(self, cmap=None):
     """
     Make matplotlib use specified colourmap. By default will use
     **self.cmap**
     """
     if cmap is None:
         cmap = self.cmap
     else:
         plt.set_cmap(cmap)
         return
     plt.register_cmap(name=cmap.name, cmap=cmap)
     plt.set_cmap(cmap)
예제 #22
0
파일: plots.py 프로젝트: Neocher/neupy
def draw_countour(xgrid, ygrid, target_function):
    output = np.zeros((xgrid.shape[0], ygrid.shape[0]))

    for i, x in enumerate(xgrid):
        for j, y in enumerate(ygrid):
            output[j, i] = target_function(x, y)

    X, Y = np.meshgrid(xgrid, ygrid)

    plt.register_cmap(name='BlueRed', data=blue_red_cmap)
    plt.contourf(X, Y, output, 50, alpha=.75, cmap='BlueRed')
    plt.colorbar()
def drawgraph(graphobj, filename):
    mycolormap = makecolormap()
    plt.register_cmap(name='BlueRed', data=mycolormap)
    plt.rcParams['image.cmap'] = 'BlueRed'

    # I've kept these in for the syntax: they're different ways to auto-arrange the nodes.
#    position = nx.graphviz_layout(graphobj.graph,prog='neato')
#    position = nx.spectral_layout(graphobj.graph)
    position = nx.spring_layout(graphobj.graph, weight='weight') #I like this best. It positions nodes closer based on the strength of their connections.

    nx.draw_networkx(graphobj.graph, pos=position, nodelist=graphobj.nodes_ordered, node_color=graphobj.nodeweights, cmap='BlueRed')
    #forget about edge colorings for now, they don't look very good. may worry about those later.
    plt.savefig(filename)
    plt.close()
예제 #24
0
def smooth_colormap(colors, name='cmap1'):
    to_rgb = clr.ColorConverter().to_rgb
    colors = [(p, to_rgb(c)) for p, c in colors]
    result = {'red': [], 'green': [], 'blue': []}
    for index, item in enumerate(colors):
        pos, color = item
        if pos is not None:
            r, g, b = color
            result['red'].append([pos, r, r])
            result['green'].append([pos, g, g])
            result['blue'].append([pos, b, b])
    cmap = clr.LinearSegmentedColormap(name, result)
    plt.register_cmap(name=name, cmap=cmap)
    return cmap
 def default_cmap():
     invert_if_black_bg = lambda v: (1 - v) if black_bg else v
     base_brightness_local = invert_if_black_bg(base_brightness)
     end_brightness = invert_if_black_bg(0)
     avg = np.average([base_brightness_local, end_brightness])
     c_range = ((0, base_brightness_local, base_brightness_local),
                (.33, base_brightness_local, avg),
                (.67, avg, end_brightness),
                (1, end_brightness, end_brightness))
     c_dict = {r: c_range for r in ['red', 'green', 'blue']}
     cmap_name = 'bright_bw'
     cmap = LinearSegmentedColormap(cmap_name, c_dict)
     plt.register_cmap(cmap=cmap)
     return cmap
예제 #26
0
파일: cmap.py 프로젝트: syrte/handy
def make_cubehelix(*args, **kwargs):
    """make_cubehelix(start=0.5, rotation=-1.5, gamma=1.0,
                   start_hue=None, end_hue=None,
                   sat=None, min_sat=1.2, max_sat=1.2,
                   min_light=0., max_light=1.,
                   n=256., reverse=False, name='custom_cubehelix')
    """
    from palettable.cubehelix import Cubehelix
    cmap = Cubehelix.make(*args, **kwargs).mpl_colormap
    register = kwargs.setdefault("register", False)
    if register:
        plt.register_cmap(cmap=cmap)
        plt.rc('image', cmap=cmap.name)
    return cmap
예제 #27
0
def angleColorMap(cmap=plt.cm.RdBu_r, cmap2=plt.cm.RdGy, name='angled',
                  start_1=0, midpoint_1=0.5, stop_1=1,
                  start_2=0, midpoint_2=0.5, stop_2=1):
    '''
    The idea here is that after your midpoint, you start going back down to
    zero. Now we try to make this work so that you have four colors total (so
    that +- 90 have different colors)

    Input
    -----
      cmap : The matplotlib colormap to be altered

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

    # regular index to compute the colors
    reg_index_1 = np.hstack([
        np.linspace(start_1, midpoint_1, 64, endpoint=False),
        np.linspace(midpoint_1, stop_1, 64, endpoint=True)
    ])
    reg_index_2 = np.hstack([
        np.linspace(start_2, midpoint_2, 64, endpoint=False),
        np.linspace(midpoint_2, stop_2, 65, endpoint=True)
    ])

    reg_index = np.hstack([reg_index_1, reg_index_2])

    # shifted index to match the data
    shift_index = np.linspace(0, 1, 257)

    for ri, si in zip(reg_index, shift_index):
        if si < 0.5:
            r, g, b, a = cmap(ri)
        else:
            r, g, b, a = cmap2(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 = LinearSegmentedColormap(name, cdict)
    plt.register_cmap(cmap=newcmap)

    return newcmap
예제 #28
0
def drawPMF(pmf, config):
    fig = plt.figure(1, figsize=(2, 2))

    cdict3 = {'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, 1.0)),

         'alpha':  ((0.0, 0.0, 0.0),
                    (1.0, 1.0, 1.0))
        }
    plt.register_cmap(name='test', data=cdict3)

    min1, bin1, max1, min2, bin2, max2 = getInfoPMF(pmf)
    PMF = getPMF(pmf, min1, bin1, max1, min2, bin2, max2)
    for i in config['selections']:
        cx, cy, r = [float(i) for i in config['selections'][i].split(",")]
        cx, cy, r = int((cx - min1 - bin1/2.)/bin1), int((cy - min2 - bin2/2.)/bin2), (r - min1 - bin1/2.)/bin1
        ny,nx = PMF.shape
        x, y = np.ogrid[-cy:ny-cy, -cx:nx-cx]
        mask = x*x + y*y < r*r

        PMF_mask = PMF*mask
        plt.imshow(PMF_mask, cmap="test", origin='lower', interpolation="none", extent=[min2, max2, min1, max1], vmin=0.0, vmax=0.1)
        plt.text(cx*bin1, cy*bin2, i.upper())


    # correction
    X, Y = np.meshgrid(PMF.columns, PMF.index)
    P = np.exp(-PMF/(T*kB))
    corr = 1/(np.sin(X*np.pi/180)*np.sin(Y*np.pi/180))
    P_corr = P*corr
    PMF_corr = -1*kB*T*np.log(P_corr)

    plt.imshow(PMF_corr, cmap="jet", origin='lower', interpolation="none", extent=[min2, max2, min1, max1], vmin=0.0, vmax=20, alpha=0.7)

    plt.axes().xaxis.set_major_locator(MultipleLocator(60))
    plt.axes().xaxis.set_minor_locator(MultipleLocator(20))
    plt.axes().yaxis.set_major_locator(MultipleLocator(60))
    plt.axes().yaxis.set_minor_locator(MultipleLocator(20))

    plt.tight_layout()
    plt.savefig("basins.svg")
    plt.show()
예제 #29
0
def plot_transparent_hexbin(ax, func, xlims, ylims, gridsize, color):
    cdict = {'red':   ((0., color[0], color[0]), (1., color[0], color[0])),
             'green': ((0., color[1], color[1]), (1., color[1], color[1])),
             'blue':  ((0., color[2], color[2]), (1., color[2], color[2])),
             'alpha': ((0., 0., 0.), (1., 1., 1.))}

    new_cmap = LinearSegmentedColormap('Custom', cdict)
    plt.register_cmap(cmap=new_cmap)

    coords = get_hexbin_coords(ax, xlims, ylims, gridsize)
    c = func(coords)
    x, y = coords.T

    ax.hexbin(x.ravel(), y.ravel(), c.ravel(),
              cmap=new_cmap, linewidths=0., edgecolors='none',
              gridsize=gridsize, vmin=0., vmax=1., zorder=1)
예제 #30
0
def TS_cmap(direc):
    plt.register_cmap(name='inferno', cmap=colormaps.inferno)
    plt.register_cmap(name='inferno_r', cmap=colormaps.inferno)
    plt.register_cmap(name='viridis', cmap=colormaps.viridis_r)
    plt.register_cmap(name='viridis_r', cmap=colormaps.viridis_r)
    cmap = 'inferno'
    if direc == -1:
        cmap = 'inferno_r'
    return cmap
예제 #31
0
        pan = fig.add_subplot(111)
        pan.errorbar(mF, frac, yerr=yerr, fmt='bo')
        pan.plot(mFforplot, gaussian(mFforplot, sigma, x0))
    return x0, dx0


cdictAll = {
    'red': ((0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 0.0, 0.0),
            (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)),
    'green': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 1.0, 1.0),
              (0.75, 0.0, 0.0), (1.0, 1.0, 1.0)),
    'blue': ((0.0, 1.0, 1.0), (0.25, 0.0, 0.0), (0.5, 0.0, 0.0),
             (0.75, 1.0, 1.0), (1.0, 1.0, 1.0))
}
allColors = mpl.colors.LinearSegmentedColormap('allColors', cdictAll)
plt.register_cmap(cmap=allColors)

S = 2
s = 2 * S + 1
theoryFile = np.load('SynDimBandStructure_F2_n7_Chern1.npz')
kList = theoryFile['kList']
E = theoryFile['E']
m = theoryFile['m']
pops = theoryFile['pops']  #[:,0,:]

modeTheory = np.zeros((kList.size, s))
sigmaModeTheory = np.zeros((kList.size, s))
fitGoodTheoryList = np.ones((kList.size, s), dtype=bool)
sigmaArrayTheory = np.ones(pops.shape) * 0.0001
for bandInd in np.arange(s):
    for Kind in range(kList.size):
예제 #32
0
import numpy as np

import matplotlib
#matplotlib.use('Agg')
from matplotlib import rcParams as rc
from matplotlib import pyplot as plot

from pylab import rcParams
from pylab import fromfile

import util
import azimuthal as az

from colormaps import cmaps
for key in cmaps:
    plot.register_cmap(name=key, cmap=cmaps[key])

### Sizes ###
sizes = np.array([1.0, 0.3, 0.1, 0.03])
size_labels = ["cm", "hcm", "mm", "hmm"]

###############################################################################

### Input Parameters ###


def new_argument_parser(description="Plot azimuthal density profiles."):
    parser = argparse.ArgumentParser()

    # Frame Selection
    parser.add_argument(
예제 #33
0
def main(inference_type: str = "K",
         batch_size: int = 1,
         test_path: str = None,
         weights: str = None,
         merge: bool = False,
         stage: str = "test",
         limit: int = 20,
         confidence: float = 0.1,
         visualize: bool = True):

    keras_model = MobileDetectNetModel.complete_model()

    if weights is not None:
        keras_model.load_weights(weights, by_name=True)

    images_done = 0

    if test_path is not None:
        import cv2

        if stage != 'test':
            from generator import MobileDetectNetSequence
            seq = MobileDetectNetSequence.create_augmenter(stage)
        else:
            seq = None

        images_full = []
        images_input = []
        images_scale = []

        for r, d, f in os.walk(test_path):
            for file in f:
                image_full = cv2.imread(os.path.join(r, file))
                image_input = cv2.resize(image_full, (224, 224))

                scale_width = image_full.shape[1] / 224
                scale_height = image_full.shape[0] / 224
                images_scale.append((scale_width, scale_height))

                if stage != 'test':
                    seq_det = seq.to_deterministic()
                    image_aug = (seq_det.augment_image(image_input).astype(np.float32) / 127.5) - 1.
                else:
                    image_aug = image_input.astype(np.float32) / 127.5 - 1.

                images_full.append(image_full)
                images_input.append(image_aug)

                images_done += 1

                if images_done == limit:
                    break

            if images_done == limit:
                break

        x_test = np.array(images_input)
    else:
        x_test = np.random.random((limit, 224, 224, 3))

    x_cold = np.random.random((batch_size, 224, 224, 3))

    if inference_type == 'K':
        keras_model.predict(x_cold)
        t0 = time.time()
        model_outputs = keras_model.predict(x_test)
        t1 = time.time()
    elif inference_type == 'TF':
        tf_engine = keras_model.tf_engine()
        tf_engine.infer(x_cold)
        t0 = time.time()
        model_outputs = tf_engine.infer(x_test)
        t1 = time.time()
    elif inference_type == 'FP32':
        tftrt_engine = keras_model.tftrt_engine(precision='FP32', batch_size=batch_size)
        tftrt_engine.infer(x_cold)
        t0 = time.time()
        model_outputs = tftrt_engine.infer(x_test)
        t1 = time.time()
    elif inference_type == 'FP16':
        tftrt_engine = keras_model.tftrt_engine(precision='FP16', batch_size=batch_size)
        tftrt_engine.infer(x_cold)
        t0 = time.time()
        model_outputs = tftrt_engine.infer(x_test)
        t1 = time.time()
    elif inference_type == 'INT8':
        tftrt_engine = keras_model.tftrt_engine(precision='INT8', batch_size=batch_size)
        tftrt_engine.infer(x_cold)
        t0 = time.time()
        model_outputs = tftrt_engine.infer(x_test)
        t1 = time.time()
    else:
        raise ValueError("Invalid inference type")

    print('Time: ', t1 - t0)
    print('FPS: ', x_test.shape[0]/(t1 - t0))

    if not visualize:
        return

    if len(model_outputs) == 2:
        classes, bboxes = model_outputs

    # TF / TensorRT models won't output regions (not useful for production)
    elif len(model_outputs) == 3:
        regions, bboxes, classes = model_outputs
    else:
        raise ValueError("Invalid model length output")

    if test_path is not None:
        import matplotlib.pyplot as plt
        from matplotlib.colors import LinearSegmentedColormap

        # get colormap
        ncolors = 256
        color_array = plt.get_cmap('viridis')(range(ncolors))

        # change alpha values
        color_array[:, -1] = np.linspace(0.0, 1.0, ncolors)

        # create a colormap object
        map_object = LinearSegmentedColormap.from_list(name='viridis_alpha', colors=color_array)

        # register this new colormap with matplotlib
        plt.register_cmap(cmap=map_object)

        for idx in range(0, len(images_full)):

            rectangles = []
            for y in range(0, 7):
                for x in range(0, 7):

                    if classes[idx, y, x, 0] >= confidence:
                        rect = [
                            int(bboxes[idx, int(y), int(x), 0] * 224),
                            int(bboxes[idx, int(y), int(x), 1] * 224),
                            int(bboxes[idx, int(y), int(x), 2] * 224),
                            int(bboxes[idx, int(y), int(x), 3] * 224)]
                        rectangles.append(rect)

            if merge:
                rectangles, merges = cv2.groupRectangles(rectangles, 1, eps=0.75)

            scale_width, scale_height = images_scale[idx]

            for rect in rectangles:
                cv2.rectangle(images_full[idx],
                              (int(rect[0]*scale_width), int(rect[1]*scale_height)),
                              (int(rect[2]*scale_width), int(rect[3]*scale_height)),
                              (0, 255, 0), 5)

            plt.imshow(cv2.cvtColor(images_full[idx], cv2.COLOR_BGR2RGB), alpha=1.0, aspect='auto')
            plt.imshow(
                cv2.resize(classes[idx].reshape((7, 7)),
                           (images_full[idx].shape[1], images_full[idx].shape[0])),
                interpolation='nearest', alpha=0.5, cmap='viridis_alpha', aspect='auto')
            plt.show()
예제 #34
0
#!/opt/local/bin/python

# --------------------------------------------------------------------------- #

# My handrolled modules.
import nemo

# Import required modules.
import cmocean
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# Register the balance colormap.
plt.register_cmap(name='speed', cmap=cmocean.cm.speed)

# --------------------------------------------------------------------------- #

# Specify where the input data lives.
homedir = '/Users/munday/Documents/Projects/ORCHESTRA/NEMO/'
nemodir = 'trunk/NEMOGCM/CONFIG/DRM-ORCH0083-LIM3/EXP00/'

# Specify the names of the different files that I want to load from.
filename = 'TIDY/ARCHIVE/1948/U/ORCH0083-LIM3_19481227_U_d05.nc'
gridfile = 'TIDY/ARCHIVE/MESH/mesh_mask.nc'

# --------------------------------------------------------------------------- #

# Load the coordinates.
glamu = np.squeeze(nemo.load_field('glamu', homedir, nemodir, gridfile, 'U'))
gphiu = np.squeeze(nemo.load_field('gphiu', homedir, nemodir, gridfile, 'U'))
#     pickle.dump(dvals, f)
#     pickle.dump(pwr, f)
#     f.close()

# # # # # # # # # # # # # # # # # #
# plot decision boundaries
fig = plt.figure(figsize=(9, 5.5))
ax = plt.subplot(1, 1, 1)
x1_mesh, x2_mesh, class_mesh = predict_bound_class(model_clf.model,
                                                   train_df,
                                                   model_clf.n_outputs,
                                                   opt_thr=opt_thr)
# custom colormap for contour
vmin, vmax = 0, 2
rel_cmap = relegator_cmap()
plt.register_cmap(cmap=rel_cmap)
cont = ax.contourf(x1_mesh,
                   x2_mesh,
                   class_mesh,
                   alpha=0.45,
                   cmap='RelegatorCMap',
                   vmin=vmin,
                   vmax=vmax,
                   levels=[-0.5, 0.5, 1.5, 2.5])
# cbar = fig.colorbar(cont)

if 'regress' in model_type:
    plot_xs(X_train, y_train, ax)
else:
    plot_xs(X_train, y_train[:, 1], ax)
# plt.title('noise = ' + str(noise) + ', angle = ' + str(angle) + ', epochs = ' + str(n_epochs))
예제 #36
0
import itertools
import numpy as np
import tkinter as tk
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as cs

cdict = {'red':   ((0.0,  0.173, 0.173),
                   (1.0,  0.925, 0.925)),

         'green': ((0.0,  0.067, 0.067),
                   (1.0, 0.384, 0.384)),

         'blue':  ((0.0,  0.027, 0.027),
                   (1.0,  0.196, 0.196))}
plt.register_cmap(name='RustPlanet', data=cdict)
REWARD_COLORS = cm.get_cmap('RustPlanet')
MAP_COLORS = {b'B':"#3a0e00",
              b'F':"#933111",
              b'S':"#933111",
              b'U':"#d65b33",}


class NegotiableMarsExplorer(NegotiableGame):


    def __init__(self, mdps, true_mdp=None, ws=None, gamma=0.95, matrix_form=True, render_scale=1):
        self.scale = render_scale
        self.tt_rewards = np.zeros(self.I)
        super(NegotiableMarsExplorer, self).__init__(mdps,true_mdp, ws, gamma, matrix_form)
예제 #37
0
def plot_image(img_obj,
               roi_list=None,
               slice_id="all",
               roi_mask=None,
               file_path=None,
               file_name="plot",
               g_range=None):
    """

    :param img_obj:
    :param roi_list:
    :param slice_id:
    :param roi_mask:
    :param file_path:
    :param file_name
    :param g_range
    :return:
    """

    # Skip if the input image is not available
    if img_obj.is_missing:
        return

    # Determine grey level range
    if g_range is None:
        g_range = [np.nan, np.nan]
    else:
        g_range = deepcopy(g_range)

    # Adapt unset intensity ranges
    if img_obj.modality == "PT":
        # PET specific settings
        if np.isnan(g_range[0]):
            g_range[0] = 0.0

        if np.isnan(g_range[1]):
            g_range[1] = np.max(img_obj.get_voxel_grid())

    elif img_obj.modality == "CT":
        # CT specific settings
        if np.isnan(g_range[0]):
            g_range[0] = -1024.0

        if np.isnan(g_range[1]):
            g_range[1] = np.max(img_obj.get_voxel_grid())

    elif img_obj.modality == "MR":
        # MR specific settings
        if np.isnan(g_range[0]):
            g_range[0] = np.min(img_obj.get_voxel_grid())

        if np.isnan(g_range[1]):
            g_range[1] = np.max(img_obj.get_voxel_grid())

    # Create custom colour map for rois ###################################

    # Import custom color map function
    from matplotlib.colors import LinearSegmentedColormap

    # Define color map. The custom color map goes from transparent black to semi-transparent green and is used as an overlay.
    cdict = {
        'red': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'green': ((0.0, 0.0, 0.0), (1.0, 0.6, 0.6)),
        'blue': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'alpha': ((0.0, 0.0, 0.0), (1.0, 0.4, 0.4))
    }

    # Create map and register
    custom_roi_cmap = LinearSegmentedColormap("colour_roi", cdict)
    plt.register_cmap(cmap=custom_roi_cmap)

    # Define colour map for base images ################################
    # Determine modality and set colour map used.
    if img_obj.modality == "PT":
        img_colour_map = "gist_yarg"
    elif img_obj.modality == "CT":
        img_colour_map = "gist_gray"
    else:
        img_colour_map = "gist_gray"

    # Check type of slice_id variable
    if isinstance(slice_id, str):
        if slice_id == "all":
            roi_flag = None
            slice_id = np.arange(start=0, stop=img_obj.size[0])
        elif slice_id == "all_roi":
            roi_flag = "all"
            slice_id = None
        elif slice_id == "roi_center":
            roi_flag = "center"
            slice_id = None
        elif slice_id == "img_center":
            roi_flag = None
            slice_id = int(np.floor(img_obj.size[0] / 2))
        else:
            raise ValueError(
                "%s is not a valid entry for identifying one or more slices for plotting.",
                slice_id)
    else:
        roi_flag = None

    # Plot without roi ################################################
    # If no rois are present, iterate over slices only
    if roi_list is None:

        # Cast slice_id to list, if it isn't a list. This allows iteration.
        if not type(slice_id) is list:
            slice_id = [slice_id]

        # Iterate over slices
        for curr_slice in slice_id:

            # Set file name
            if file_path is not None:
                plot_file_name = os.path.join(
                    file_path,
                    check_string(file_name + "_" +
                                 img_obj.get_export_descriptor() + "_" +
                                 str(curr_slice) + ".png"))
            else:
                plot_file_name = None

            # Get image and roi slices
            img_slice = img_obj.get_voxel_grid()[curr_slice, :, :]

            # Determine minimum and maximum luminance:
            img_g_range = crop_image_intensity(img_slice=img_slice,
                                               g_range=g_range,
                                               modality=img_obj.modality)

            # Plot
            plotter(slice_list=[img_slice],
                    colour_map_list=[img_colour_map],
                    file_name=plot_file_name,
                    intensity_range=img_g_range,
                    enhance=img_obj.spacing[2])

    # Plot with roi ##################################################
    else:

        # Iterate over rois in roi_list
        for curr_roi in roi_list:

            # Find roi center slice
            if slice_id is None:
                if roi_flag == "center":
                    slice_id = curr_roi.get_center_slice()
                elif roi_flag == "all":
                    slice_id = curr_roi.get_all_slices()

            # Cast slice_id to list, if it isn't a list. This allows iteration.
            if not (isinstance(slice_id, list)
                    or isinstance(slice_id, np.ndarray)):
                slice_id = [slice_id]

            # Iterate over slices
            for curr_slice in slice_id:

                # Set file name
                if file_path is not None:
                    plot_file_name = os.path.join(
                        file_path,
                        check_string(file_name + "_" +
                                     img_obj.get_export_descriptor() +
                                     curr_roi.get_export_descriptor() + "_" +
                                     str(curr_slice) + ".png"))
                else:
                    plot_file_name = None

                # Get image and roi slices
                img_slice = img_obj.get_voxel_grid()[curr_slice, :, :]
                if roi_mask == "intensity" and curr_roi.roi_intensity is not None:
                    roi_slice = curr_roi.roi_intensity.get_voxel_grid()[
                        curr_slice, :, :]
                elif roi_mask == "morphology" and curr_roi.roi_morphology is not None:
                    roi_slice = curr_roi.roi_morphology.get_voxel_grid()[
                        curr_slice, :, :]
                else:
                    roi_slice = curr_roi.roi.get_voxel_grid()[curr_slice, :, :]

                # Determine minimum and maximum luminance:
                img_g_range = crop_image_intensity(img_slice=img_slice,
                                                   g_range=g_range,
                                                   modality=img_obj.modality)

                # Create figure
                plotter(slice_list=[img_slice, roi_slice],
                        colour_map_list=[img_colour_map, "colour_roi"],
                        file_name=plot_file_name,
                        intensity_range=img_g_range,
                        enhance=img_obj.spacing[2])
예제 #38
0
    for istep in range(nsteps):
        r = rgbdata[istep, 0]
        g = rgbdata[istep, 1]
        b = rgbdata[istep, 2]
        rdata.append((stepaxis[istep], r, r))
        gdata.append((stepaxis[istep], g, g))
        bdata.append((stepaxis[istep], b, b))

    mpl_data = {"red": rdata, "green": gdata, "blue": bdata}

    return mpl_data


mpl_data = RGBToPyCmap(turbo_colormap_data)
plt.register_cmap(name="turbo",
                  data=mpl_data,
                  lut=turbo_colormap_data.shape[0])

mpl_data_r = RGBToPyCmap(turbo_colormap_data[::-1, :])
plt.register_cmap(name="turbo_r",
                  data=mpl_data_r,
                  lut=turbo_colormap_data.shape[0])

Turbo = plt.get_cmap('turbo')

if __name__ == "__main__":

    XX, YY = np.meshgrid(np.linspace(0, 1, 100), np.linspace(0, 1, 100))
    ZZ = np.sqrt(XX**2 + YY**2)

    plt.figure()
예제 #39
0
def map_num_users():

    mpl.rcParams['font.size'] = 4.4

    ###########################################################################################
    fig = plt.figure(3)
    #Custom adjust of the subplots
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(111)

    m = Basemap(llcrnrlon=-9, \
                    llcrnrlat=3.8, \
                    urcrnrlon=-1.5, \
                    urcrnrlat = 11, \
                    resolution = 'h', \
                    projection = 'tmerc', \
                    lat_0 = 7.38, \
                    lon_0 = -5.30)

    subpref_users = read_in_subpref_num_users()
    # read the shapefile archive
    s = m.readshapefile(
        '/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE',
        'subpref')

    max7s = 1
    min7s = 10000000
    for subpref in subpref_users.keys():
        if subpref_users[subpref] > max7s:
            max7s = subpref_users[subpref]
        if subpref_users[subpref] < min7s:
            min7s = subpref_users[subpref]

    max7s = float(max7s)
    print "max", (max7s)
    print "min", (min7s)

    scaled_weight = defaultdict(int)
    for i in range(256):
        scaled_weight[i] = defaultdict(int)
    for subpref in subpref_users.keys():
        scaled_weight[subpref] = (subpref_users[subpref] - min7s) / (max7s -
                                                                     min7s)

#     values = range(256)
#     jet = cm = plt.get_cmap('jet')
#     cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
#     scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

# define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16)
    cdict = {
        'red': ((0.0, 1.0, 1.0), (1.0, 0.9, 1.0)),
        'green': ((0.0, 1.0, 1.0), (1.0, 0.03, 0.0)),
        'blue': ((0.0, 1.0, 1.0), (1.0, 0.16, 0.0))
    }
    custom_map = LinearSegmentedColormap('custom_map', cdict, N=10000)
    plt.register_cmap(cmap=custom_map)

    subpref_coord = read_in_subpref_lonlat()

    shp = ShapeFile(
        r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')
    dbf = dbflib.open(
        r'/home/sscepano/DATA SET7S/D4D/SubPrefecture/GEOM_SOUS_PREFECTURE')

    for npoly in range(shp.info()[0]):
        shpsegs = []
        shpinfo = []

        shp_object = shp.read_object(npoly)
        verts = shp_object.vertices()
        rings = len(verts)
        #print shp_object

        for ring in range(rings):
            print ring
            lons, lats = zip(*verts[ring])
            #        if max(lons) > 721. or min(lons) < -721. or max(lats) > 91. or min(lats) < -91:
            #            raise ValueError,msg
            x, y = m(lons, lats)
            shpsegs.append(zip(x, y))

            if ring == 0:
                shapedict = dbf.read_record(npoly)
            print shapedict
            name = shapedict["ID_DEPART"]
            subpref_id = shapedict["ID_SP"]
            #             print name, subpref_id
            # add information about ring number to dictionary.
            shapedict['RINGNUM'] = ring + 1
            shapedict['SHAPENUM'] = npoly + 1
            shpinfo.append(shapedict)
        #print subpref_id
        #print name
        lines = LineCollection(shpsegs, antialiaseds=(1, ))
        colorVal = custom_map(subpref_users[subpref_id])
        #         colorVal = scaled_weight[subpef]
        lines.set_facecolors(colorVal)
        lines.set_edgecolors('gray')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)
예제 #40
0
def plotmaps(data, verbose = False, filter ="WORLD", var="od550aer",
             plotdir="./"):
    """plot aerocom standard maps

    Will plot every supplied time step"""

    if not isinstance(data, GriddedData):
        raise TypeError("Need pyaerocom.GriddedData as input")
    #define color bar;
    #will be moved somewhere else and variable specific at some point
    colorbar_levels = [0., 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8,
                       0.9, 1.0]

    colorbar_ticks = [0., 0.02, 0.04, 0.06, 0.08, 0.1, 0.3, 0.5, 0.7, 0.9]
    aod_data = {
        'red': ((0., 0, 0), (0.07, 0, 0), (0.1, 0.678, 0.678,), (0.26, 1, 1), (0.85, 1, 1), (1, 0.545, 0.545)),
        'green': ((0., 0, 0), (0.07, 1, 1), (0.24, 1, 1), (0.91, 0, 0), (1, 0, 0)),
        'blue': ((0., 1, 1), (0.07, 1, 1), (0.1, 0.133, 0.133), (0.25, 0, 0), (1, 0, 0))}

    colormap = LinearSegmentedColormap('aod_jet', aod_data)
    plt.register_cmap(cmap = colormap)
    TIME_VAR_NAME = 'time'

    PlotDailyFlag = False
    PlotMonthlyFlag = True

    for model in data:
        #assume that we have single cube for the moment
        #iterate over the time dimension
        cube = data[model].data
        #model = 'AATSR_ORAC_v4.01'

        cube.coord('latitude').guess_bounds()
        cube.coord('longitude').guess_bounds()

        #plot daily data
        if PlotDailyFlag:
            for time_sub_cube in cube.slices_over(TIME_VAR_NAME):
                pre_grid_areas = iris.analysis.cartography.area_weights(time_sub_cube)
                #pdb.set_trace()
                #print(time_sub_cube)

                # Perform the area-weighted mean for each of the datasets using the
                # computed grid-box areas.
                weighted_mean = time_sub_cube.collapsed(['latitude', 'longitude'],
                                                        iris.analysis.MEAN,
                                                        weights = pre_grid_areas)

                time = (unit.num2date(time_sub_cube.coord(TIME_VAR_NAME).points,
                                      time_sub_cube.coord(TIME_VAR_NAME).units.name,
                                      time_sub_cube.coord(TIME_VAR_NAME).units.calendar))

                date = str(time[0]).split(' ')[0].replace('-','')
                Year = date[0:4]
                TsStr = 'm'+date
                PlotType = 'MAP'

                title = " ".join([var, date, 'mean: {:6.3f}'.format(float(weighted_mean.data))])
                #ABS550_AER_an2012_mALLYEAR_WORLD_ZONALOBS_AERONETSky.ps.png
                #OD550_AER_an2017_d20171125_WORLD_MAP.ps.png
                plotfilename = os.path.join(plotdir, '_'.join([var, "an" + Year, TsStr, filter, PlotType]) + ".png")
                if verbose:
                    print(plotfilename)
                plot = iplt.pcolormesh(time_sub_cube[:, :], cmap = colormap, vmin=0., vmax=max(colorbar_levels))
                # pdb.set_trace()
                plot.axes.set_aspect(1.8)
                LatsToPlot = time_sub_cube.coord(axis='X').points
                LonsToPlot = time_sub_cube.coord(axis='Y').points
                axis = plt.axis([LatsToPlot.min(), LatsToPlot.max(), LonsToPlot.min(), LonsToPlot.max()])
                ax = plot.axes
                ax.annotate('source: AEROCOM', xy=(0.88, 0.04), xycoords='figure fraction',
                            horizontalalignment='right', fontsize=10, bbox=dict(boxstyle='square', facecolor='none',
                                                                                edgecolor='black'))
                ax.annotate(model, xy=(-174., -83.), xycoords='data', horizontalalignment='left', fontsize=13,
                            color='black', bbox=dict(boxstyle='square', facecolor='white', edgecolor='none', alpha=0.7))

                # plt.ylabel(_title(plot_defn.coords[0], with_units=True))
                # plot_defn = iplt._get_plot_defn(cube, mode, ndims)

                plt.colorbar(spacing='uniform', ticks=colorbar_ticks,
                             boundaries=colorbar_levels, extend='max')

                ax.coastlines()
                ax.set_xticks([-180., -120., -60., 0., 60, 120, 180], crs=ccrs.PlateCarree())
                ax.set_yticks([-90., -60, -30, 0., 30, 60, 90], crs=ccrs.PlateCarree())
                lon_formatter = LongitudeFormatter(number_format='.1f', degree_symbol='')
                lat_formatter = LatitudeFormatter(number_format='.1f', degree_symbol='')
                ax.xaxis.set_major_formatter(lon_formatter)
                ax.yaxis.set_major_formatter(lat_formatter)

                plt.xlabel = 'longitude'
                plt.ylabel = 'latitude'

                plt.title(title)
                plt.savefig(plotfilename, dpi=300)
                plt.close()
                #pdb.set_trace()

        elif PlotMonthlyFlag:
            #calculate monthly data

            iris.coord_categorisation.add_month(cube, TIME_VAR_NAME, name='month_number')
            iris.coord_categorisation.add_year(cube, TIME_VAR_NAME, name='month_year')
            cube_monthly = cube.aggregated_by(['month_number', 'month_year'], iris.analysis.MEAN)

            for time_sub_cube in cube_monthly.slices_over(TIME_VAR_NAME):
                pre_grid_areas = iris.analysis.cartography.area_weights(time_sub_cube)
                # pdb.set_trace()
                # print(time_sub_cube)

                # Perform the area-weighted mean for each of the datasets using the
                # computed grid-box areas.
                weighted_mean = time_sub_cube.collapsed(['latitude', 'longitude'],
                                                        iris.analysis.MEAN,
                                                        weights=pre_grid_areas)

                time = (unit.num2date(time_sub_cube.coord(TIME_VAR_NAME).points,
                                      time_sub_cube.coord(TIME_VAR_NAME).units.name,
                                      time_sub_cube.coord(TIME_VAR_NAME).units.calendar))

                date = str(time[0]).split(' ')[0].replace('-', ' ')[0:7]
                Year = date[0:4]
                TsStr = 'm' + date[-2:]
                PlotType = 'MAP'

                title = " ".join([var, date, 'mean: {:6.3f}'.format(float(weighted_mean.data))])
                # ABS550_AER_an2012_mALLYEAR_WORLD_ZONALOBS_AERONETSky.ps.png
                # OD550_AER_an2017_d20171125_WORLD_MAP.ps.png
                plotfilename = os.path.join(plotdir, '_'.join([var, "an" + Year, TsStr, filter, PlotType]) + ".png")
                if verbose:
                    print(plotfilename)
                LatsToPlot = time_sub_cube.coord(axis='X').points
                LonsToPlot = time_sub_cube.coord(axis='Y').points
                xticks = [-180., -120., -60., 0., 60, 120, 180]
                yticks = [-90., -60, -30, 0., 30, 60, 90]
                plot_ts_map(time_sub_cube, title, plotfilename, LatsToPlot, LonsToPlot, colorbar_ticks,
                            colorbar_levels, colormap, model, xticks, yticks)
예제 #41
0
def draw_redflag(m, lons, lats,
                 model, dsize, background,
                 location, lat, lon,
                 RUNDATE, VALIDDATE, fxx,
                 alpha, half_box, barb_thin,
                 RH=25, SPEED=6.7,
                 Fill=False,
                 Contour=False,
                 Fill_Potential=False):
    # Generalized criteria for red flag warning
    # Winds (gusts) greater than 6.7 m/s and RH < 25%
    rf_RH = RH
    rf_WIND = SPEED

    # Get Data
    H_gust = get_hrrr_variable(RUNDATE, 'GUST:surface',
                               model=model, fxx=fxx,
                               outDIR='/uufs/chpc.utah.edu/common/home/u0553130/temp/',
                               verbose=False, value_only=True)
    H_rh = get_hrrr_variable(RUNDATE, 'RH:2 m',
                             model=model, fxx=fxx,
                             outDIR='/uufs/chpc.utah.edu/common/home/u0553130/temp/',
                             verbose=False, value_only=True)
    
    RedFlag = np.logical_and(H_gust['value'] >rf_WIND, H_rh['value'] < rf_RH)

    if Fill:
        masked = np.ma.array(RedFlag)
        masked[masked == 0] = np.ma.masked 
        m.pcolormesh(lons, lats, masked,
                     cmap="YlOrRd_r",
                     alpha=alpha,
                     zorder=5, latlon=True)

    if Contour:
        try:
            CS = m.contour(lons, lats, RedFlag, 
                            latlon=True,
                            colors='darkred',
                            linewidths=.75,
                            levels=[0],
                            zorder=10)
        except:
            # maybe there isn't any contours in this domain
            pass

    if Fill_Potential:
        cdict3 = {'red':  ((0.0,  1.0, 1.0),
                           (0.5,  0.5, 0.5),
                           (0.5,  1.0, 1.0),
                           (1.0,  0.4, 0.4)),
                  'green': ((0.0,  1.0, 1.0),
                            (0.5,  0.5, 0.5),
                            (0.5,  0.4, 0.4),
                            (1.0,  0.0, 0.0)),
                  'blue':  ((0.0,  1.0, 1.0),
                            (0.5,  0.5, 0.5),
                            (0.5,  0.0, 0.0),
                            (1.0,  0.0, 0.0))
                }
        plt.register_cmap(name='FirePot', data=cdict3)
        
        # Definate Red Flag Area:
        RED_FLAG = np.logical_and(H_rh['value'] < rf_RH,
                                  H_gust['value'] > rf_WIND)
        # Linear Equation
        b = (rf_RH-rf_WIND)*(rf_RH/rf_WIND)
        z = -(rf_RH/rf_WIND)*(H_rh['value']-H_gust['value'])+b
        
        m.pcolormesh(lons, lats, z,
                     cmap="FirePot",
                     alpha=alpha,
                     vmax=200, vmin=-200,
                     zorder=3,
                     latlon=True)
        cb = plt.colorbar(orientation='horizontal', pad=pad, shrink=shrink)
        cb.set_label(r'Red Flag Potential')
        
    plt.xlabel(r'Red Flag Criteria: Winds > %s m s$\mathregular{^{-1}}$ and RH < %s%%' % (SPEED,RH))
예제 #42
0
파일: darkjet.py 프로젝트: bastorer/SPINSpy
# Check to see if DISPLAY variable set, if not
# then use the Agg background
try:
    if not (os.environ["DISPLAY"]):
        matplotlib.use('Agg')
except:
    if not ('matplotlib' in sys.modules.keys()):
        matplotlib.use('Agg')
import matplotlib.cm as colmap
import matplotlib.colors as mplc
import matplotlib.pyplot as plt
import numpy as np

## Through a jet, darkly.

## Create DarkJet
## ------
col_list = colmap.jet(range(256))
darken = np.tile((1 - 0.5 / np.cosh(np.linspace(-10, 10, 256))).reshape(
    (256, 1)), [1, col_list.shape[1]])

col_list = col_list * darken  # Apply the darkening

# Matplotlib defaults to rgba, not rgb.
# Reset the transparency values now.
col_list[:, 3] = 1.

darkjet = mplc.ListedColormap(col_list, 'darkjet', 256)
plt.register_cmap(cmap=darkjet)
## ------
예제 #43
0
import numpy as np
import astropy.units as u
import astropy.constants as c
from astropy.time import Time
import glob

import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import colormaps as cmaps
plt.register_cmap(name='viridis', cmap=cmaps.viridis)
plt.set_cmap(cmaps.viridis)




def gpfinder(wfall_file, thresh):

    data = np.load(wfall_file)
    deltat = float(data['tbin_microsecond'])*u.microsecond
    tstart = Time(float(data['t0']),format='mjd')
    wfall = data['I']

    #wfall = wfall[2000:-5000,:,0]+wfall[2000:-5000,:,-1]
    wfall = wfall[:,0,0,:] + wfall[:,0,-1,:]
    wfall = wfall.T
    wfall = wfall/wfall.mean(axis=1,keepdims=True) -1
    med_std = np.nanmedian(np.std(wfall,axis=1))
    wfall[np.abs(np.std(wfall,axis=1)-med_std)>0.01,:]=np.nan
    
예제 #44
0
        plt.subplots_adjust(top=1.0,
                            bottom=0.0,
                            left=0.0,
                            right=1.0,
                            wspace=0.0,
                            hspace=0.0)

    plt.savefig(output, bbox_inches='tight', dpi=dpi)
    plt.close('all')


# register custom maps
plt.register_cmap(cmap=colors.LinearSegmentedColormap(
    'red', {
        'red': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.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, 0.0, 1.0), (1.0, 1.0, 1.0))
    }))

plt.register_cmap(cmap=colors.LinearSegmentedColormap(
    'green', {
        'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
        'red': ((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, 0.0, 1.0), (1.0, 1.0, 1.0))
    }))

plt.register_cmap(cmap=colors.LinearSegmentedColormap(
    'blue', {
        'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
예제 #45
0
"""
Package containing plotting customizations and routines.
"""
import pkg_resources  # NOQA: E402
from matplotlib import pyplot  # NOQA: E402
from figstyle.style import colourWheel, dashesStyles, width, golden_ratio  # NOQA: F401
from figstyle.turbo_colormap import mpl_turbo_data  # NOQA: F401

# Load style file
style_path = pkg_resources.resource_filename(
    "figstyle", "data/paper_double_fig.mplstyle"
)
pyplot.style.use(style_path)

# register the "turbo" colormap
pyplot.register_cmap(name="turbo", data=mpl_turbo_data, lut=256)
예제 #46
0
    #                 #   (0.75,1.0, 1.0),
    #                    (1.0, 1.0, 1.0))
    #
    # blue_red = LinearSegmentedColormap('BlueRed', cdict4)
    ncolors = 256
    color_array = plt.get_cmap('coolwarm')(range(ncolors))

    # change alpha values
    color_array[:, -1] = np.linspace(1.0, 0.0, ncolors)

    # create a colormap object
    map_object = LinearSegmentedColormap.from_list(name='rainbow_alpha',
                                                   colors=color_array)

    # register this new colormap with matplotlib
    plt.register_cmap(cmap=map_object)

    fig = plt.figure(figsize=plt.figaspect(0.5))
    ax = fig.add_subplot(1, 2, 1, projection="3d")
    plot = ax.scatter(xx.flatten(),
                      yy.flatten(),
                      zz.flatten(),
                      s=20,
                      c=pc,
                      cmap='rainbow_alpha',
                      vmin=-20,
                      vmax=+20)
    ax.set_xlabel('X Axes')
    ax.set_ylabel('Y Axes')
    ax.set_zlabel('Z Axes')
    ax.set_title(
예제 #47
0
from scipy.ndimage import map_coordinates

import matplotlib
#matplotlib.use('Agg')
from matplotlib import rcParams as rc
from matplotlib import pyplot as plot

from pylab import rcParams
from pylab import fromfile

import util
from readTitle import readTitle

import colormaps as cmaps

plot.register_cmap(name='viridis', cmap=cmaps.viridis)
plot.register_cmap(name='inferno', cmap=cmaps.inferno)
plot.register_cmap(name='plasma', cmap=cmaps.plasma)
plot.register_cmap(name='magma', cmap=cmaps.magma)

save_directory = "squarePolarGasDensityMaps"

### Get FARGO Parameters ###
# Create param file if it doesn't already exist
param_fn = "params.p"
if not os.path.exists(param_fn):
    command = "python pickleParameters.py"
    split_command = command.split()
    subprocess.Popen(split_command)
fargo_par = pickle.load(open(param_fn, "rb"))
예제 #48
0
cmaps['dkc_v'] = {
    'colors': colors,
    'position': position,
    'min': -100,
    'max': 100
}

z = cmaps['wdtd_z']
v = cmaps['wdtd_v']

vel_max = 100
vels_array = np.linspace(-vel_max, vel_max, 11)
vticks = np.ndarray.tolist(vels_array)

ref_cmap = make_cmap(z['colors'], position=z['position'], bit=True)
plt.register_cmap(cmap=ref_cmap)
plts['ReflectivityQC'] = {
    'cmap': ref_cmap,
    'vmn': z['min'],
    'vmx': z['max'],
    'title': 'Reflectivity',
    'cbticks': [0, 15, 30, 50, 60],
    'cblabel': 'dBZ'
}
plts['Ref'] = plts['ReflectivityQC']

vel_cmap = make_cmap(v['colors'], position=v['position'], bit=True)
plt.register_cmap(cmap=vel_cmap)
plts['Velocity'] = {
    'cmap': vel_cmap,
    'vmn': v['min'],
예제 #49
0
import numpy as np
import healpy as hp
from matplotlib.colors import LogNorm

import pyathena as pa
import pyathena.synthetic_observations as syn

import glob, os

base = '/tigress/changgoo/'
sourcedir = '../'
cmap = syn.load_planck_cmap(
    '{}/misc/Planck_Parchment_RGB.txt'.format(sourcedir))
cmap.set_bad('white', 0.)
cmap.set_under(cmap.colors[0])
plt.register_cmap(cmap=cmap)
plt.rcParams['image.cmap'] = 'planck'
plt.rcParams['font.size'] = 20
plt.rcParams['figure.figsize'] = (12, 6)
plt.rcParams['figure.dpi'] = 150

# magnetar
import sys
sys.path.append('{}/Sources/magnetar/'.format(base))
from bvisual import lic

from astropy.io import fits
from astropy.wcs import WCS

from reproject import reproject_from_healpix, reproject_to_healpix, reproject_interp
예제 #50
0
# -*- coding: utf-8 -*-
"""
This code is written to generate the Chlorophyll colormap.
Therefore, instead of importing it, it should just be run.
I'm looking into a more proper way to do this.

Created on Mon Aug 13 2018

@author: joe
"""

import igor.binarywave as igoribw
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt

chl = igoribw.load('Chlorophyll.ibw')
colordata = np.transpose(chl['wave']['wData'])
chlor = {}
L = len(np.transpose(colordata))
chlor['red'] = [(i / (L - 1), colordata[0][i] / 65533, colordata[0][i] / 65533)
                for i, x in enumerate(colordata[0])]
chlor['green'] = [(i / (L - 1), colordata[1][i] / 65533,
                   colordata[1][i] / 65533)
                  for i, x in enumerate(colordata[0])]
chlor['blue'] = [(i / (L - 1), colordata[2][i] / 65533,
                  colordata[2][i] / 65533) for i, x in enumerate(colordata[0])]
chlorophyll = LinearSegmentedColormap('Chlorophyll', chlor)
plt.register_cmap(cmap=chlorophyll)
예제 #51
0
#!/opt/local/bin/python

# --------------------------------------------------------------------------- #

# My handrolled modules.
import nemo

# Import required modules.
import cmocean
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# Register the thermal colormap.
plt.register_cmap(name='ice', cmap=cmocean.cm.ice)

plt.ioff()

# --------------------------------------------------------------------------- #

# Specify where the input data lives.
homedir = '~/ORCHESTRA/NEMO/'
nemodir = 'trunk/NEMOGCM/CONFIG/CORE2NYF-ORCH0083-LIM3/EXP00/'

# Specify the names of the different files that I want to load from.
filename = 'TIDY/ARCHIVE/1948/I/ORCH0083-LIM3_19481227_I_d05.nc'
gridfile = 'TIDY/ARCHIVE/MESH/mesh_mask.nc'

# --------------------------------------------------------------------------- #

# Load the coordinates.
예제 #52
0
from matplotlib.patches import Wedge
from matplotlib import __version__ as mplv
import matplotlib.pyplot as plt
from spacepy import __path__ as basepath
from spacepy.datamodel import dmcopy
import spacepy.datamanager as dman
from .. import config
from .spectrogram import *
from .utils import *
from .carrington import *
from .colourmaps import plasma as _plasma
from .colourmaps import plasma_r as _plasma_r
from .colourmaps import viridis as _viridis
from .colourmaps import viridis_r as _viridis_r

plt.register_cmap(name='plasma', cmap=_plasma)
plt.register_cmap(name='plasma_r', cmap=_plasma_r)
plt.register_cmap(name='viridis', cmap=_viridis)
plt.register_cmap(name='viridis_r', cmap=_viridis_r)

def plot(*args, **kwargs):
    '''Convenience wrapper for matplotlib's plot function

    As with matplotlib's plot function, *args* is a variable length
    argument, allowing for multiple *x*, *y* pairs, each with optional 
    format string. For full details, see matplotlib.pyplot.plot

    Other Parameters
    ----------------
    smartTimeTicks : boolean
        If True then use applySmartTimeTicks to set x-axis labeling
예제 #53
0
# +
# plotting
imageDims = (14, 14)
figureImageDims = (2, 3)
figureTableDims = (5, 4)
fontScale = 1

# set transparent mask for low attention areas
# cdict = plt.get_cmap("gnuplot2")._segmentdata
cdict = {
    "red": ((0.0, 0.0, 0.0), (0.6, 0.8, 0.8), (1.0, 1, 1)),
    "green": ((0.0, 0.0, 0.0), (0.6, 0.8, 0.8), (1.0, 1, 1)),
    "blue": ((0.0, 0.0, 0.0), (0.6, 0.8, 0.8), (1.0, 1, 1))
}
cdict["alpha"] = ((0.0, 0.35, 0.35), (1.0, 0.65, 0.65))
plt.register_cmap(name="custom", data=cdict)


def showTableAtt(table, words, tax=None):
    '''
    Question attention as sns heatmap
    '''
    if tax is None:
        fig2, bx = plt.subplots(1, 1)
        bx.cla()
    else:
        bx = tax

    sns.set(font_scale=fontScale)

    steps = len(table)
예제 #54
0
# Turn the lon/lat of the bins into 2 dimensional arrays ready
# for conversion into projected coordinates
lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins)

# convert the bin mesh to map coordinates:
xs, ys = m(lon_bins_2d, lat_bins_2d)  # will be plotted using pcolormesh

# define custom colormap, white -> nicered, #E6072A = RGB(0.9,0.03,0.16)
cdict = {
    'red': ((0.0, 1.0, 1.0), (1.0, 0.9, 1.0)),
    'green': ((0.0, 1.0, 1.0), (1.0, 0.03, 0.0)),
    'blue': ((0.0, 1.0, 1.0), (1.0, 0.16, 0.0))
}
custom_map = LinearSegmentedColormap('custom_map', cdict)
plt.register_cmap(cmap=custom_map)

# add histogram squares and a corresponding colorbar to the map:
plt.pcolormesh(xs, ys, density, cmap="custom_map")

cbar = plt.colorbar(orientation='horizontal',
                    shrink=0.625,
                    aspect=20,
                    fraction=0.5,
                    pad=0.02)
cbar.set_label('Number of Jobs', size=26)
#plt.clim([0,100])

# translucent blue scatter plot of jobs above histogram:
x, y = m(list(lons), list(lats))
m.plot(x,
예제 #55
0
                   (1.0, 1.0, 1.0))


# Now we will use this example to illustrate 3 ways of
# handling custom colormaps.
# First, the most direct and explicit:

blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)

# Second, create the map explicitly and register it.
# Like the first method, this method works with any kind
# of Colormap, not just
# a LinearSegmentedColormap:

blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2)
plt.register_cmap(cmap=blue_red2)

# Third, for LinearSegmentedColormap only,
# leave everything to register_cmap:

plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg
plt.register_cmap(name='BlueRedAlpha', data=cdict4)

# Make some illustrative fake data:

x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x,y)
Z = np.cos(X) * np.sin(Y) * 10

# Make the figure:
예제 #56
0
    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        sys.exit(2)

    #%% Set cmap if SCM
    if cmap_name.startswith('SCM'):
        if cmap_name.endswith('_r'):
            exec("cmap = {}.reversed()".format(cmap_name[:-2]))
        else:
            exec("cmap = {}".format(cmap_name))
    elif cmap_name == 'insar':
        cdict = tools_lib.cmap_insar()
        plt.register_cmap(
            cmap=mpl.colors.LinearSegmentedColormap('insar', cdict))
        cmap = 'insar'
    else:
        cmap = cmap_name

    #%% Get info and Read data
    if gdal.IdentifyDriver(infile):  ## If Geotiff or grd
        geotiff = gdal.Open(infile)
        data = geotiff.ReadAsArray()
        if data.ndim > 2:
            print('\nERROR: {} has multiple bands and cannot be displayed.\n'.
                  format(infile),
                  file=sys.stderr)
            sys.exit(2)

        length, width = data.shape
예제 #57
0
def shiftedColorMap(cmap, data=False, start=0, midpoint=0.5, stop=1.0, 
                    set=True, register=False, 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 `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.
    '''
    if type(data) == np.ndarray:
        vmax = data.max()
        vmin = data.min()
        midpoint = 1 - vmax/(vmax + abs(vmin))


    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)

    if set:
        plt.set_cmap(newcmap)

    if register:
        plt.register_cmap(cmap=newcmap)

    return newcmap
예제 #58
0
    "darkpurple", colorcet.linear_bmw_5_95_c89)
# add gkr theme for velocity
div_blue_black_red_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
    "div_blue_black_red", colorcet.diverging_gkr_60_10_c40)
# add RdBu_r theme for velocity
div_blue_red_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
    "div_blue_red", colorcet.diverging_bwr_55_98_c37)
# add glasbey_bw for cell annotation in white background
glasbey_white_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
    "glasbey_white", colorcet.glasbey_bw_minc_20)
# add glasbey_bw_minc_20_maxl_70 theme for cell annotation in dark background
glasbey_dark_cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
    "glasbey_dark", colorcet.glasbey_bw_minc_20_maxl_70)

# register cmap
plt.register_cmap("zebrafish", zebrafish_cmap)
plt.register_cmap("fire", fire_cmap)
plt.register_cmap("darkblue", darkblue_cmap)
plt.register_cmap("darkgreen", darkgreen_cmap)
plt.register_cmap("darkred", darkred_cmap)
plt.register_cmap("darkpurple", darkpurple_cmap)
plt.register_cmap("div_blue_black_red", div_blue_black_red_cmap)
plt.register_cmap("div_blue_red", div_blue_red_cmap)
plt.register_cmap("glasbey_white", glasbey_white_cmap)
plt.register_cmap("glasbey_dark", glasbey_dark_cmap)

_themes = {
    "fire": {
        "cmap": "fire",
        "color_key_cmap": "rainbow",
        "background": "black",
예제 #59
0
import string
import glob
import random
import sys
import numpy as np
import scipy as sp
import scipy.stats
import matplotlib
import matplotlib.pyplot as plt
import itertools as it
import types
import pdb

wrb_cmap=matplotlib.colors.LinearSegmentedColormap.from_list('wrb',colors=['white','red','black'])
wrb_cmap.set_bad([0.82,0.82,0.82])
plt.register_cmap(cmap=wrb_cmap)

worb_cmap=matplotlib.colors.LinearSegmentedColormap.from_list('worb',colors=['white','orange','red',[0.5,0,0],'black'])
worb_cmap.set_bad([0.82,0.82,0.82])
plt.register_cmap(cmap=worb_cmap)

worb2_cmap=matplotlib.colors.LinearSegmentedColormap.from_list('worb2',colors=['white','orange','red',[0.5,0,0],'black'])
worb2_cmap.set_bad([1,1,1])
plt.register_cmap(cmap=worb2_cmap)

dekker_cmap=matplotlib.colors.LinearSegmentedColormap.from_list('dekker',colors=[[1,1,1],[1,0.65,0],[1,0,0],[0.35,0,0]])
dekker_cmap.set_bad([0.82,0.82,0.82])
plt.register_cmap(cmap=dekker_cmap)

bwr_cmap=matplotlib.colors.LinearSegmentedColormap.from_list('bwr',colors=['blue','white','red'])
bwr_cmap.set_bad([0.82,0.82,0.82])
예제 #60
0
def _mpl_cm(name, colorlist):
    cmap = LinearSegmentedColormap.from_list(name, colorlist, N=256)
    register_cmap("cet_" + name, cmap=cmap)