def sot_color_table(measurement): """ Returns one of the standard color tables for SOT files (following osdc convention). The relations between observation and color have been defined in hinode.py """ try: r, g, b = { 'intensity': (r0, g0, b0), }[measurement] except KeyError: raise ValueError( "Invalid (or not supported) SOT type. Valid values are: " "intensity") cdict = create_cdict(r, g, b) return colors.LinearSegmentedColormap(f'Hinode SOT {measurement:s}', cdict)
def ncl_grnd_hflux(): r=np.array([0,8,16,24,32,40,48,85,133,181,230,253,253,253,253,253,253,253,253,253,253,253]) g=np.array([253,222,189,157,125,93,60,85,133,181,230,230,181,133,85,60,93,125,157,189,224,253]) b=np.array([253,253,253,253,253,253,253,253,253,253,253,230,181,133,85,48,40,32,24,16,8,0]) xsize=np.arange(np.size(r)) r = r/255. g = g/255. b = b/255. red = [] blue = [] green = [] for i in range(len(xsize)): xNorm=np.float(i)/(np.float(np.size(r))-1.0) red.append([xNorm,r[i],r[i]]) green.append([xNorm,g[i],g[i]]) blue.append([xNorm,b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} my_coltbl = colors.LinearSegmentedColormap('NCL_GRND_HFLUX_COLTBL',colorDict) return my_coltbl
def ncl_perc_11Lev(): r=np.array([202,89,139,96,26,145,217,254,252,215,150]) g=np.array([202,141,239,207,152,207,239,224,141,48,0]) b=np.array([200,252,217,145,80,96,139,139,89,39,100]) xsize=np.arange(np.size(r)) r = r/255. g = g/255. b = b/255. red = [] blue = [] green = [] for i in range(len(xsize)): xNorm=np.float(i)/(np.float(np.size(r))-1.0) red.append([xNorm,r[i],r[i]]) green.append([xNorm,g[i],g[i]]) blue.append([xNorm,b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} my_coltbl = colors.LinearSegmentedColormap('NCL_PERC_11LEV_COLTBL',colorDict) return my_coltbl
def ncl_snow(): r=np.array([255,237,205,153,83,50,50,5,5,10,44,106]) g=np.array([255,250,255,240,189,166,150,112,80,31,2,44]) b=np.array([255,194,205,178,159,150,180,176,140,150,70,90]) xsize=np.arange(np.size(r)) r = r/255. g = g/255. b = b/255. red = [] blue = [] green = [] for i in range(len(xsize)): xNorm=np.float(i)/(np.float(np.size(r))-1.0) red.append([xNorm,r[i],r[i]]) green.append([xNorm,g[i],g[i]]) blue.append([xNorm,b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} ncl_snow_coltbl = colors.LinearSegmentedColormap('NCL_SNOW_COLTBL',colorDict) return ncl_snow_coltbl
def cmap_from_rgb_file(name, fname): """ Create a colormap from a RGB .csv file. name : str Name of the colormap. fname : str Filename of data file. Relative to the sunpy colormap data directory. Returns ------- cmap : matplotlib.colors.LinearSegmentedColormap """ data = np.loadtxt(cmap_data_dir / fname, delimiter=',') if data.shape[1] != 3: raise RuntimeError( f'RGB data files must have 3 columns (got {data.shape[1]})') cdict = create_cdict(data[:, 0], data[:, 1], data[:, 2]) return colors.LinearSegmentedColormap(name, cdict)
def make_colormap(color): """ Create LinearSegmentedColormap ranging from white to the given color. Color can be given in any legal color format. Bad color is set to white. """ try: r, g, b = mc.colorConverter.to_rgb(color) except: raise ValueError('Illegal color specification: %s' % color.__repr__) cm = mc.LinearSegmentedColormap( color.__str__(), { 'red': [(0.0, 1.0, 1.0), (1.0, r, r)], 'green': [(0.0, 1.0, 1.0), (1.0, g, g)], 'blue': [(0.0, 1.0, 1.0), (1.0, b, b)] }) cm.set_bad(color=bad_color) # light yellow return cm
def _gen_cmap_registry(): """ Generate a dict mapping standard colormap names to standard colormaps, as well as the reversed colormaps. """ cmap_d = {**cmaps_listed} for name, spec in datad.items(): cmap_d[name] = ( # Precache the cmaps at a fixed lutsize.. colors.LinearSegmentedColormap(name, spec, _LUTSIZE) if 'red' in spec else colors.ListedColormap(spec['listed'], name) if 'listed' in spec else colors.LinearSegmentedColormap.from_list( name, spec, _LUTSIZE)) # Generate reversed cmaps. for cmap in list(cmap_d.values()): rmap = cmap.reversed() cmap._global = True rmap._global = True cmap_d[rmap.name] = rmap return cmap_d
def Getcmap(Name=None, RGBPoints=None, N=100): '''Create a color map.''' if Name is not None: return cm.get_cmap(Name, N) elif RGBPoints is not None: Pts = np.array(RGBPoints) Pts = Pts.reshape(-1, 4) Ncol = Pts.shape[0] rtpl = [] gtpl = [] btpl = [] for i in range(Ncol): rtpl.append((Pts[i, 0], Pts[i, 1], Pts[i, 1])) gtpl.append((Pts[i, 0], Pts[i, 2], Pts[i, 2])) btpl.append((Pts[i, 0], Pts[i, 3], Pts[i, 3])) cdict = {'red': rtpl, 'green': gtpl, 'blue': btpl} return cm.get_cmap(cols.LinearSegmentedColormap(Name, cdict, N=N), N) else: raise ("Error: Cannot Set-up Color Map")
def tcamt(): r = np.array([255,230,200,180,150,120,80,55,30,15,225,180,150,120,80,60,40,30,20,220,192,160,128,112,72,60,45,40,250,240,225,200,180,160,140,120,100]) g = np.array([255,255,255,250,245,245,240,210,180,160,255,240,210,185,165,150,130,110,100,220,180,140,112,96,60,40,30,0,240,220,190,160,140,120,100,80,60]) b = np.array([255,225,190,170,140,115,80,60,30,15,255,250,250,250,245,245,240,235,210,255,255,255,235,220,200,180,165,160,230,210,180,150,130,110,90,70,50]) xsize=np.arange(np.size(r)) r = r/255. g = g/255. b = b/255. red = [] blue = [] green = [] for i in range(len(xsize)): xNorm=np.float(i)/(np.float(np.size(r))-1.0) red.append([xNorm,r[i],r[i]]) green.append([xNorm,g[i],g[i]]) blue.append([xNorm,b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} tcamt = colors.LinearSegmentedColormap('TCAMT',colorDict) return tcamt
def make_color_map(colorsToMap): # Example: # WHITE ->> 4 colors ->> colorDictionary["red"] = [0.0, None, 1.0], <<- [0/4, r1 from None, r2 from WHITE] # RED [0.25, 1.0, 1.0], <<- [1/4, r1 from WHITE, r2 from RED] # BLUE [0.5, 1.0, 0.0], <<- [1/2, r1 from RED, r2 from BLUE] # PURPLE [0.75, 0.0, 0.5], <<- [3/4, r1 from BLUE, r2 from PURPLE] # [1.0, 0.5, None] <<- [4/4, r1 from Purple, r2 from None] nColorsToMap = len(colorsToMap) # e.g. 4 colorsToMap colors = [[None for j in range(3)] for i in range(nColorsToMap + 2)] # e.g. colors = [[None, None, None], # [None, None, None], # [None, None, None], # [None, None, None], # [None, None, None], # [None, None, None]] nColors = len(colors) # e.g. 6 colors for i in range(nColorsToMap): colors[i + 1] = colorsToMap[i] # e.g. colors = [None, None, None], # [ 1.0, 1.0, 1.0], WHITE # [ 1.0, 0.0, 0.0], RED # [ 0.0, 0.0, 1.0], BLUE # [ 0.5, 0.0, 0.5], PURPLE # [None, None, None] colorDictionary = {"red": [], "green": [], "blue": []} for i in range(nColors - 1): r1, g1, b1 = colors[i] r2, g2, b2 = colors[i + 1] fraction = float(i) / float(nColorsToMap) colorDictionary["red"].append([fraction, r1, r2]) colorDictionary["green"].append([fraction, g1, g2]) colorDictionary["blue"].append([fraction, b1, b2]) return mcolors.LinearSegmentedColormap("CustomMap", colorDictionary)
def dim_cmap(cmap, factor=.3, to_white=True): """ Dim a colormap to white, or to black. """ assert factor >= 0 and factor <= 1, ValueError( 'Dimming factor must be larger than 0 and smaller than 1, %s was passed.' % factor) if to_white: dimmer = lambda c: 1 - factor * (1 - c) else: dimmer = lambda c: factor * c cdict = cmap._segmentdata.copy() for c_index, color in enumerate(('red', 'green', 'blue')): color_lst = list() for value, c1, c2 in cdict[color]: color_lst.append((value, dimmer(c1), dimmer(c2))) cdict[color] = color_lst return _colors.LinearSegmentedColormap('%s_dimmed' % cmap.name, cdict, _cm.LUTSIZE)
def get_colormap(cmap_name, lims): if cmap_name in ('light symmetric', 'dark symmetric', 'symmetric'): n_points = 256 if cmap_name in ('light symmetric', 'symmetric'): org_cmap = plt.get_cmap('RdBu_r') neg_cmap = get_part_of_cmap(org_cmap, 0.0, 0.5, n_points) pos_cmap = get_part_of_cmap(org_cmap, 0.5, 1.0, n_points) elif cmap_name == 'dark symmetric': neg_color_vals = { 'red': ((0.0, 0.6, 0.6), (0.6, 0.0, 0.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 1.0, 1.0), (0.4, 0.8, 0.8), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (0.8, 0.8, 0.8), (1.0, 0.0, 0.0)), } neg_cmap = mcolors.LinearSegmentedColormap('', neg_color_vals) pos_cmap = plt.get_cmap('afmhot') max_abs = np.max(np.abs(lims)) min_val = lims[0] max_val = lims[1] z_range = max_val - min_val if min_val < 0 < max_val: # Negative neg_fraction = abs(min_val) / z_range n_neg_points = int(neg_fraction * n_points) neg_low = 1.0 - abs(min_val) / max_abs neg_vals = np.linspace(neg_low, 1.0, n_neg_points) neg_colors = neg_cmap(neg_vals) # Positive pos_fraction = abs(max_val) / z_range n_pos_points = int(pos_fraction * n_points) pos_high = abs(max_val) / max_abs pos_vals = np.linspace(0.0, pos_high, n_pos_points) pos_colors = pos_cmap(pos_vals) # Combine negative and positive. colors = np.vstack((neg_colors, pos_colors)) cmap = mcolors.LinearSegmentedColormap.from_list('', colors) elif 0 <= min_val <= max_val: cmap = pos_cmap elif min_val <= max_val <= 0: cmap = neg_cmap else: cmap = plt.get_cmap(cmap_name) return cmap
def q3heatmap(path_d): dict_d = {} dict_d_temp = {} df_corr = pd.DataFrame() allFiles = glob.glob(path_d + "/*.csv") for file_ in allFiles: df = pd.read_csv(file_, index_col=0) max_gain = ( (df.iloc[0]['Close']) - (df.iloc[len(df) - 1]['Close'])) / (df.iloc[len(df) - 1]['Close']) s = (file_.split('\\')[-1]) dict_d[s[:-4]] = max_gain df_corr[s[:-4]] = (df['Gain_or_Loss_%']) df_corr = df_corr.dropna() corr = df_corr.corr() cdict = { 'blue': ( (0.0, 0.0, 0.0), # no red at 0 (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white (1.0, 0.8, 0.8)), # set to 0.8 so its not too bright at 1 'red': ( (0.0, 0.8, 0.8), # set to 0.8 so its not too bright at 0 (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white (1.0, 0.0, 0.0)), # no green at 1 'green': ( (0.0, 0.0, 0.0), # no blue at 0 (0.5, 1.0, 1.0), # all channels set to 1.0 at 0.5 to create white (1.0, 0.0, 0.0)) # no blue at 1 } GnRdBe = colors.LinearSegmentedColormap('GnRdBe', cdict) fig, ax = plt.subplots(1) data = corr p = ax.pcolormesh(data, cmap=GnRdBe, vmin=-1, vmax=1) fig.colorbar(p, ax=ax) fig.set_size_inches(10, 10) plt.show()
def get_continuous_cmap(clist, float_list=None, ctype: str = 'dec'): '''Creates and returns a color map that can be used in heat map figures. If float_list is not provided, colour map graduates linearly between each color in clist. If float_list is provided, each color in clist is mapped to the respective location in float_list. Parameters ---------- clist: list of colors float_list: list of floats between 0 and 1, same length as clist. Must start with 0 and end with 1. type: str 'rgb', 'hex', 'dec', Default 'dec' Returns ---------- colour map ''' # Convert hex to decimal rgb and 255rgb to decimal rgb if ctype == 'hex': rgb_list = [rgb_to_dec(hex_to_rgb(_hexcolor)) for _hexcolor in clist] elif ctype == 'rgb': rgb_list = [rgb_to_dec(_color) for _color in clist] else: rgb_list = clist # Get distances if float_list: pass else: float_list = list(np.linspace(0, 1, len(rgb_list))) cdict = dict() for num, col in enumerate(['red', 'green', 'blue']): col_list = [[float_list[i], rgb_list[i][num], rgb_list[i][num]] for i in range(len(float_list))] cdict[col] = col_list cmp = mcolors.LinearSegmentedColormap('my_cmp', segmentdata=cdict, N=256) return cmp
def register_cmap(name=None, cmap=None, data=None, lut=None): """ Add a colormap to the set recognized by :func:`get_cmap`. It can be used in two ways:: register_cmap(name='swirly', cmap=swirly_cmap) register_cmap(name='choppy', data=choppydata, lut=128) In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap` instance. The *name* is optional; if absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*. The second case is deprecated. Here, the three arguments are passed to the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer, and the resulting colormap is registered. Instead of this implicit colormap creation, create a `.LinearSegmentedColormap` and use the first case: ``register_cmap(cmap=LinearSegmentedColormap(name, data, lut))``. """ cbook._check_isinstance((str, None), name=name) if name is None: try: name = cmap.name except AttributeError as err: raise ValueError("Arguments must include a name or a " "Colormap") from err if isinstance(cmap, colors.Colormap): cmap_d[name] = cmap return if lut is not None or data is not None: cbook.warn_deprecated( "3.3", message="Passing raw data via parameters data and lut to " "register_cmap() is deprecated. Instead use: " "register_cmap(" "cmap=LinearSegmentedColormap(name, data, lut))") # For the remainder, let exceptions propagate. if lut is None: lut = mpl.rcParams['image.lut'] cmap = colors.LinearSegmentedColormap(name, data, lut) cmap_d[name] = cmap
def load_cmaps(): """Returns a list of "bad" colormap names, and registers them.""" # Iterate through screenshots files = sorted( glob.glob( os.path.join(os.path.dirname(__file__), '..', 'cmaps', '*.png'))) screenshot_data = { 'screenshot' + str(i + 1): png2rgb(file) for i, file in enumerate(files) } # Register colormaps and return list cmaps = [] for name, data in {**_hardcoded_data, **screenshot_data}.items(): if isinstance(data, dict): cmap = mcolors.LinearSegmentedColormap(name, data, lut) else: cmap = mcolors.LinearSegmentedColormap.from_list(name, data, lut) mcm.cmap_d[name] = cmap cmaps.append(name) return cmaps
def level_colormap(levels, cmap=None): """Make a colormap based on an increasing sequence of levels""" # Spread the colours maximally nlev = len(levels) S = np.arange(nlev, dtype='float') / (nlev - 1) A = cmap(S) # Normalize the levels to interval [0,1] levels = np.array(levels, dtype='float') L = (levels - levels[0]) / (levels[-1] - levels[0]) # Make the colour dictionary R = [(L[i], A[i, 0], A[i, 0]) for i in range(nlev)] G = [(L[i], A[i, 1], A[i, 1]) for i in range(nlev)] B = [(L[i], A[i, 2], A[i, 2]) for i in range(nlev)] cdict = dict(red=tuple(R), green=tuple(G), blue=tuple(B)) # Use return colors.LinearSegmentedColormap('%s_levels' % cmap.name, cdict, 256)
def correlation_to_rgb(attributes): cex = np.max(np.abs(attributes)) if cex == 0: cdict = Colormap.create_white_cmap_dict() else: cdict = Colormap.create_bidirectional_corr_cmap_dict(cex) cdict_orig = deepcopy(cdict) # Scale the attribute values in cdict from 0 to 1 for i in range(0, len(cdict['red'])): cdict['red'][i] = ((cdict['red'][i][0] + cex) / (2 * cex), cdict['red'][i][1], cdict['red'][i][2]) for i in range(0, len(cdict['green'])): cdict['green'][i] = ((cdict['green'][i][0] + cex) / (2 * cex), cdict['green'][i][1], cdict['green'][i][2]) for i in range(0, len(cdict['blue'])): cdict['blue'][i] = ((cdict['blue'][i][0] + cex) / (2 * cex), cdict['blue'][i][1], cdict['blue'][i][2]) my_cmap = mpl_colors.LinearSegmentedColormap('my_bi_cmap', cdict, 256) my_cmap._init() new_attrib_range = Colormap.normalize(attributes, -1 * cex, cex) vColor = my_cmap(new_attrib_range)[:, 0:3] return vColor, cex, my_cmap
def get_cmap(): c = mcolors.ColorConverter().to_rgb custom_colors = [(0, 0, 0, 0),\ (0.18, 0.05, 0.05, 0.2),\ (0.28, 0, 0, 1),\ (0.4, 0.7, 0.85, 0.9),\ (0.45, 0, 0.75, 0),\ (0.6, 1, 1, 0),\ (0.75, 1, 0, 0),\ (0.92 , 0.6, 0.6, 0.6),\ (1 , 0.95, 0.95, 0.95)] cdict = {'red': [], 'green': [], 'blue': []} for i, item in enumerate(custom_colors): pos, r, g, b = item cdict['red'].append([pos, r, r]) cdict['green'].append([pos, g, g]) cdict['blue'].append([pos, b, b]) cmap = mcolors.LinearSegmentedColormap('CustomMap', cdict) cmap.set_bad(color='black') return cmap
def suvi_color_table(wavelength: u.angstrom): """ Returns one of the fundamental color tables for SUVI images. SUVI uses AIA color tables. """ try: if wavelength == 195 * u.angstrom: r, g, b = aia_wave_dict[193 * u.angstrom] elif wavelength == 284 * u.angstrom: r, g, b = aia_wave_dict[335 * u.angstrom] else: r, g, b = aia_wave_dict[wavelength] except KeyError: raise ValueError("Invalid SUVI wavelength. Valid values are " "94, 131, 171, 195, 284, 304.") # Now create the color dictionary in the correct format cdict = create_cdict(r, g, b) return colors.LinearSegmentedColormap( 'GOES-R SUVI {:s}'.format(str(wavelength)), cdict)
def dibujar(símismo, ejes, fig, args_color=None): args_color = args_color or {} vals_norm = (símismo.valores - símismo.escala[0]) / (símismo.escala[1] - símismo.escala[0]) d_clrs = _gen_d_mapacolores(colores=símismo.escala_colores) mapa_color = colors.LinearSegmentedColormap('mapa_color', d_clrs) norm = colors.Normalize(vmin=símismo.escala[0], vmax=símismo.escala[1]) cpick = cm.ScalarMappable(norm=norm, cmap=mapa_color) cpick.set_array(np.array([])) v_cols = mapa_color(vals_norm) v_cols[np.isnan(vals_norm)] = 1 símismo._dibujar_frm(ejes=ejes, color=v_cols) if símismo.unidades is not None: fig.colorbar(cpick, label=símismo.unidades, ax=ejes, **args_color) else: fig.colorbar(cpick, ax=ejes, extend='both')
def cccfcmap3(w=0.02, W=.25, g=.0, Ncolor = 256): cdict = {'red': ((0.0, 0.0, 0.0), (.5 - W, 0.0, 0.0), (.5 - w, g, g), (.5 + w, 1-g, 1-g), (.5 + W, 1.0, 1.0), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0, 0.0), (.5 - W, 0.0, 0.0), (.5 - w, 1.0, 1.0), (.5 + w, 1.0, 1.0), (.5 + W, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 1.0, 1.0), (.5 - W, 1.0, 1.0), (.5 - w, 1-g, 1-g), (.5 + w, g, g), (.5 + W, 0.0, 0.0), (1.0, 0.0, 0.0))} return colors.LinearSegmentedColormap('my_colormap', cdict, 256)
def make_colormap(seq): """Return a LinearSegmentedColormap. seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ import matplotlib.colors as mcolors cdict = {'red': [], 'green': [], 'blue': []} # make a lin_space with the number of records from seq. x = np.linspace(0, 1, len(seq)) for i in range(len(seq)): segment = x[i] tone = seq[i] cdict['red'].append([segment, tone, tone * .5]) cdict['green'].append([segment, tone, tone]) cdict['blue'].append([segment, tone, tone]) return mcolors.LinearSegmentedColormap('CustomMap', cdict)
def pseudocolor(val, minval, maxval): data = { 'red': [(0.0, 1.0, 1.0), (0.1, 0.5, 0.5), (0.2, 0.0, 0.0), (0.3, 0.0, 0.0), (0.4, 0.0, 0.0), (0.5, 0.0, 0.0), (0.6, 0.0, 0.0), (0.7, 0.5, 0.5), (0.8, 1.0, 1.0), (0.9, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.1, 0.0, 0.0), (0.2, 0.0, 0.0), (0.3, 0.5, 0.5), (0.4, 1.0, 1.0), (0.5, 1.0, 1.0), (0.6, 1.0, 1.0), (0.7, 1.0, 1.0), (0.8, 1.0, 1.0), (0.9, 0.5, 0.5), (1.0, 0.0, 0.0)], 'blue': [(0.0, 1.0, 1.0), (0.1, 1.0, 1.0), (0.2, 1.0, 1.0), (0.3, 1.0, 1.0), (0.4, 1.0, 1.0), (0.5, 0.5, 0.5), (0.6, 0.0, 0.0), (0.7, 0.0, 0.0), (0.8, 0.0, 0.0), (0.9, 0.0, 0.0), (1.0, 0.0, 0.0)] } cmap = colors.LinearSegmentedColormap("mycustommap", data) val = (val - minval) / (maxval - minval) color = cmap(val) return tuple(int(x * 255) for x in color)
def subcolormap(xmin, xmax, cmap): '''Returns the part of cmap between xmin, xmax, scaled to 0,1.''' assert xmin < xmax assert xmax <= 1 cd = cmap._segmentdata.copy() colornames = ('red', 'green', 'blue') rgbmin, rgbmax = rgb_to_dict(xmin, cmap), rgb_to_dict(xmax, cmap) for k in cd: tmp = [x for x in cd[k] if x[0] >= xmin and x[0] <= xmax] if tmp == [] or tmp[0][0] > xmin: tmp = [(xmin, rgbmin[k], rgbmin[k])] + tmp if tmp == [] or tmp[-1][0] < xmax: tmp = tmp + [(xmax, rgbmax[k], rgbmax[k])] #now scale all this to (0,1) square = zip(*tmp) xbreaks = [(x - xmin) / (xmax - xmin) for x in square[0]] square[0] = xbreaks tmp = zip(*square) cd[k] = tmp return colors.LinearSegmentedColormap('local', cd, N=256)
def mpy_to_mpl_cmap(ctable, rev=False): """This function grabs a colortable with the metpy format and converts it to a table that can be easily parsed as an mpl map""" LinL = [ line.replace('(', '').replace(')', '').rstrip('\n') for line in open(ctable) ] LinL = [np.fromstring(l, dtype=float, sep=",") for l in LinL] LinL = np.vstack(LinL) if rev == True: LinL = LinL[::-1] b3 = LinL[:, 2] # value of blue at sample n b2 = LinL[:, 2] # value of blue at sample n b1 = np.linspace(0, 1, len(b2)) # position of sample n - ranges from 0 to 1 # setting up columns for list g3 = LinL[:, 1] g2 = LinL[:, 1] g1 = np.linspace(0, 1, len(g2)) r3 = LinL[:, 0] r2 = LinL[:, 0] r1 = np.linspace(0, 1, len(r2)) # creating list R = zip(r1, r2, r3) G = zip(g1, g2, g3) B = zip(b1, b2, b3) # transposing list RGB = zip(R, G, B) rgb = zip(*RGB) # print rgb # creating dictionary k = ['red', 'green', 'blue'] LinearL = dict(zip(k, rgb)) # makes a dictionary from 2 lists my_cmap = mplcol.LinearSegmentedColormap('my_colormap', LinearL) return my_cmap
def plotHeatmap(name, data, x_label='', y_label='', x_tick_labels=[], y_tick_labels=[]): #data is a 2x2 array normalized [0,1] plt.clf() fig, ax = plt.subplots() #delete top and right axis ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() ## put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ## want a more natural, table-like display ##ax.invert_yaxis() ##ax.xaxis.tick_top() ax.set_xticklabels(x_tick_labels, rotation=90, minor=False) ax.set_yticklabels(y_tick_labels, minor=False) #set colorbar cdict = { 'red': [(0.0, 1.0, 1.0), (0.01, 0.5, 0.5), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)], 'green': [(0.0, 1.0, 1.0), (0.1, 1.0, 1.0), (1.0, 0.0, 0.0)], 'blue': [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)] } my_cmap = colors.LinearSegmentedColormap('my_colormap', cdict, 256) #heatmap = ax.pcolor(data, cmap=plt.cm.Blues) heatmap = ax.pcolor(data, cmap=my_cmap, vmin=0, vmax=1) cbar = plt.colorbar(heatmap) plt.title(name) plt.xlabel(x_label) plt.ylabel(y_label) plt.plot() #save plot f_format = name.split('.')[-1] name = name.split('.')[0] plt.savefig(name + '.' + f_format, format=f_format, bbox_inches='tight')
def cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ if type(cmap) == str: cmap = get_cmap(cmap) colors_i = concatenate((linspace(0, 1., N), (0.,0.,0.,0.))) colors_rgba = cmap(colors_i) indices = linspace(0, 1., N+1) cdict = {} for ki,key in enumerate(('red','green','blue')): cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in range(N+1) ] # Return colormap object. return colors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
def ncl_radarmap(): # Radar color map from NCL r = np.array([255,255,0,0,0,9,0,8,255,255,255,221,188,121,121,295]) g = np.array([255,255,255,157,0,130,255,175,214,152,0,0,0,0,51,163]) b = np.array([255,255,255,255,255,175,0,20,0,0,0,27,54,109,160,212]) xsize=np.arange(np.size(r)) r = r/255. g = g/255. b = b/255. red = [] blue = [] green = [] for i in range(len(xsize)): xNorm=np.float(i)/(np.float(np.size(r))-1.0) red.append([xNorm,r[i],r[i]]) green.append([xNorm,g[i],g[i]]) blue.append([xNorm,b[i],b[i]]) colorDict = {"red":red, "green":green, "blue":blue} ncl_reflect_coltbl = colors.LinearSegmentedColormap('NCL_REFLECT_COLTBL',colorDict) ncl_reflect_coltbl.set_over(color='white') return ncl_reflect_coltbl
def make_colormap(seq,values=None): """Return a LinearSegmentedColormap seq: RGB-tuples. values: corresponding values (location betwen 0 and 1) """ n=len(seq) if values is None: values=np.linspace(0,1,n) doubled = list(itertools.chain.from_iterable(itertools.repeat(s, 2) for s in seq)) doubled[0] = (None,)* 3 doubled[-1] = (None,)* 3 cdict = {'red': [], 'green': [], 'blue': []} for i,v in enumerate(values): r1, g1, b1 = doubled[2*i] r2, g2, b2 = doubled[2*i + 1] cdict['red'].append([v, r1, r2]) cdict['green'].append([v, g1, g2]) cdict['blue'].append([v, b1, b2]) #print(cdict) return mcolors.LinearSegmentedColormap('CustomMap', cdict)