def load_colormap(filename): """Load a colormap defined in a text file filename is the .txt file name located in the data/ path, not the full path. list_available_colormaps() lists the available color tables """ try: if rank == 0: vals = np.loadtxt(os.path.join(DATA_PATH, filename))/255.0 n_vals = len(vals) else: vals = None if par.use_mpi: vals = mpi.COMM_WORLD.bcast(vals, root=0) colormap = ListedColormap(vals) except exceptions.IOError: print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps())) raise # color of missing pixels colormap.set_bad("gray") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colormap) colormap.set_under("white") return colormap
def main(): """ Plot the data using the row_labels as, you guessed it, row labels and the data_dict as columns. The plot will be saved as input_file.png with the previous extension removed. """ input_file = sys.argv[1] row_labels, data_dict = ParseFile(input_file) # Get the data needed. df = pd.DataFrame(data_dict, index=row_labels) # Create the dataframe. # EDIT THIS TO CHANGE FIGURE SIZE. plt.figure(figsize=(8, 11), dpi=1200) # Set colors [-5 to 5]. Can use html hex codes, recognized html colors, or rgb triplets. colors = ['#8c510a', "#bf812d", "#f5f5f5", "#f5f5f5", "#80cdc1", "#01665e"] cmap = ListedColormap(colors, name="cmap", N=6) # Change N if you have a greater range. # Set colors for over/under the bound limits. cmap.set_over("#003c30") cmap.set_under("#543005") bounds = [-20, -10, -3, 0, 3, 10, 20] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # Create the plot without y axis labels. Change 'extend' to 'both' or 'min' to make cbar extend # in opposite direction. heatmap = sns.heatmap(df, cbar=True, cbar_kws={'extend':'max'} ,cmap=cmap, norm=norm, yticklabels=False) plt.xticks(rotation=90) plt.title(input_file.split(".")[0]) out_name = input_file.split(".")[0] + ".pdf" # EDIT extension to change output format. heatmap.figure.savefig(out_name)
class Palette: def __init__(self, file_name): fichero = open(file_name, 'r') try: self.length = int(fichero.readline()) #self.dic = {} self.red = [int(x) for x in fichero.readline().split()] self.green = [int(x) for x in fichero.readline().split()] self.blue = [int(x) for x in fichero.readline().split()] sec = [] for i in range(1, self.length): sec.append((self.red[i] / 255., self.green[i] / 255., self.blue[i] / 255.)) #self.dic[i] = [self.red[i]/255., self.green[i]/255., self.blue[i]/255.] self.cm = ListedColormap(sec) self.cm.set_under(color='k', alpha=0) except: print('Error leyendo la paleta') fichero.close() def color(self, value): if value >= self.length: print('Valor de color fuera de rango') rgb = (self.red[value] / 255., self.green[value] / 255., self.blue[value] / 255.) return rgb
def PlotMFPLoczCountSubplot_3D (fig, ax, array, global_bin_max, xx, yy, component, depth, modus, unique_areas): ##### Plot MFP localizaton counts (i.e. overlap counts) for MFP 3D subplot ##### global_bin_max: overall max localization count (encompassing all win sizes) clevs = np.linspace(0, int(global_bin_max), int(global_bin_max) + 2) # Choose colormap cmap_coolwarm = pl.cm.gist_stern_r # Get the colormap colors my_cmap = cmap_coolwarm(np.arange(cmap_coolwarm.N)) # Set alpha my_cmap[:,-1] = 1 # Create new colormap my_cmap = ListedColormap(my_cmap) # set color of values below "vmin" to "gainsboro" my_cmap.set_under("white", alpha = 0.7) normalize = matplotlib.colors.Normalize(vmin = 1, vmax = global_bin_max, clip = True) if modus == "unique": contf = ax.contourf(xx, yy, array, levels = clevs, cmap = my_cmap, offset = depth, norm = normalize, extend = 'min', zdir = 'z', zorder = 0) else: contf = ax.contourf(xx, yy, array, levels = clevs, cmap = my_cmap, offset = depth, norm = normalize, extend = 'min', zdir = 'z', zorder = 0) if unique_areas != []: patch = PolygonPatch(unique_areas, facecolor = "none", edgecolor = "black", alpha = 1, zorder = 2000) return contf plt.close(fig) return patch
def PlotMFPLoczCount_2D (ax, array, global_bin_max, xx, yy, inset): ##### Plot MFP localizaton counts (i.e. overlap counts) #### array: sum of localization counts # set range and steps for colormap clevs = np.linspace(0, int(global_bin_max), int(global_bin_max) + 2) # Choose colormap cmap_coolwarm = pl.cm.gist_stern_r # Get the colormap colors my_cmap = cmap_coolwarm(np.arange(cmap_coolwarm.N)) # Set alpha my_cmap[:,-1] = 1 # Create new colormap my_cmap = ListedColormap(my_cmap) # set color of values below "vmin" to "none" my_cmap.set_under("none") normalize = matplotlib.colors.Normalize(vmin = 1, vmax = global_bin_max, clip = True) contf = ax.contourf(xx, yy, array, levels = clevs, cmap = my_cmap, norm = normalize, extend = 'min', zorder = 1) ax.set_aspect(aspect = "equal") return contf
def plot(): """Do plotting work""" cmap1 = plt.get_cmap('inferno_r') colors = list(cmap1(np.arange(10) / 10.)) cmap2 = plt.get_cmap('Pastel1') colors.extend(list(cmap2(np.arange(2) / 2.))) cmap = ListedColormap(colors) cmap.set_under('tan') cmap.set_over('white') minval = np.load('minval.npy') maxval = np.load('maxval.npy') diff = maxval - minval lons = np.load('lons.npy') lats = np.load('lats.npy') mp = MapPlot(sector='midwest', statebordercolor='white', title=(r"Diff between coldest wind chill and warmest " "air temp 29 Jan - 3 Feb 2019"), subtitle=("based on hourly NCEP Real-Time Mesoscale Analysis " "(RTMA) ending midnight CST")) levels = list(range(0, 101, 10)) levels.extend([105, 110]) mp.pcolormesh(lons, lats, diff, levels, cmap=cmap, clip_on=False, units=r"$^\circ$F", spacing='proportional') mp.postprocess(filename='test.png')
def rgb2cmap(filename, base='255'): """Function to read a rgb file (i.e. NCL colortables) and convert it to matplotlib colormap Author: Daniel Argueso @ CCRC, UNSW. Sydney (Australia) """ from matplotlib.colors import ListedColormap import re filein = open(filename) lines = filein.readlines() colors = [] for line in lines[2:]: line = re.sub('\s+', ' ', line) li = line.strip() if li: values = li.split(' ') if base == '255': new_values = [i / 255. for i in map(int, values[:3])] else: new_values = [i for i in map(float, values[:3])] colors.append(new_values) cmap = ListedColormap(colors) cmap.set_over(colors[-1]) cmap.set_under(colors[0]) return cmap
def planck_color_map(self): cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) cmap.set_bad("darkgray") cmap.set_under("white") return cmap
def planck_color_map(self): ''' Itab = [ 0, 13, 26, 39, 52, 65, 76, 77, 88, 101, 114, 127, 140, 153, 166, 179, 192, 205, 218, 231, 255] Rtab = [ 0, 10, 30, 80, 191, 228, 241, 241, 245, 248, 249.9, 242.25,204, 165, 114, 127.5, 178.5, 204, 229.5, 242.25, 252.45] Gtab = [ 0, 20, 184, 235, 239, 240, 241, 241, 240, 235, 204, 153, 76.5, 32, 0, 127.5, 178.5, 204, 229.5, 242.25, 252.45] Btab = [ 255, 255, 255, 255, 250, 245, 212, 212, 175, 130, 38.25, 12.75, 0, 32, 32, 153, 204, 229.5, 242.25, 249.9, 255] ncolors = 256 ii = np.arange(ncolors, dtype=np.float32) R = np.interp(ii, Itab, Rtab) G = np.interp(ii, Itab, Rtab) B = np.interp(ii, Itab, Rtab) ''' cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) cmap.set_bad("darkgray") cmap.set_under("white") return cmap
def get_planck_cmap(): from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) return colombi1_cmap
def get_planck_cmap(): from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap( np.loadtxt("Planck_Parchment_RGB.txt") / 255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under( "white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) return colombi1_cmap
def plot_skymap(skymap, smooth=None, decmax=None, scale=None, color_bins=40, color_palette='viridis', symmetric=False, cbar_min=None, cbar_max=None, cbar_title='Skymap', llabel=None, polar=False, fig=None, sub=None): cpalette = sns.color_palette(color_palette, color_bins) cmap = ListedColormap(cpalette.as_hex()) cmap.set_under('white') cmap.set_bad('gray') # if cbar_max and cbar_max and symmetric and (cbar_max != -cbar_min): # raise ValueError('The max/min colorbar values can\'t be symmetric') # elif cbar_max and cbar_max: # pass # elif: # skymap_min = skymap.min() # skymap_max = skymap.max() # maximum = np.max(np.abs([skymap_min, skymap_max])) # cbar_min = np.sign(skymap_min) * maximum # cbar_max = np.sign(skymap_max) * maximum # else: # cbar_min = cbar_min if cbar_min else skymap.min() # cbar_max = cbar_max if cbar_max else skymap.max() if polar: shrink = 0.6 rot = [0,-90,180] hp.orthview(skymap, half_sky=True, rot=rot, coord='C', title='', min=cbar_min, max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub) else: shrink = 1.0 hp.mollview(skymap, rot=180, coord='C', title='', min=cbar_min, max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub) hp.graticule(verbose=False) fig = plt.gcf() ax = plt.gca() image = ax.get_images()[0] cbar = fig.colorbar(image, orientation='horizontal', aspect=50, pad=0.01, fraction=0.1, ax=ax, format=FormatStrFormatter('%g'), shrink=shrink) if cbar_title: cbar.set_label(cbar_title, size=14) if not polar: ax.set_ylim(-1, 0.005) ax.annotate('0$^\circ$', xy=(1.8, -0.75), size=14) ax.annotate('360$^\circ$', xy=(-1.99, -0.75), size=14) if llabel: ax.annotate(llabel, xy=(-1.85,-0.24), size=20, color='white') return fig, ax
def pycmap(gacmap): from matplotlib.colors import ListedColormap from numpy import vstack r = gacmap.table['r'] g = gacmap.table['g'] b = gacmap.table['b'] rt = ListedColormap(vstack((r, g, b)).T) rt.set_over((r[-1], g[-1], b[-1])) rt.set_under((r[0], g[0], b[0])) rt.set_bad(color='k', alpha=0) return rt
def planck_cmap(): """ Generates the Planck CMB colormap from an input file, which stores the color values for the complete gradient. The colormap values was obtained from the following link: - https://github.com/zonca/paperplots/raw/master/data/Planck_Parchment_RGB.txt """ cmap = ListedColormap(np.loadtxt(data + 'Planck_Parchment_RGB.txt') / 255.) cmap.set_bad('black') # color of missing pixels cmap.set_under('white') # color of background return cmap
def pycmap(gacmap): from matplotlib.colors import ListedColormap from numpy import vstack r = gacmap.table['r'] g = gacmap.table['g'] b = gacmap.table['b'] rt = ListedColormap(vstack((r, g, b)).T) rt.set_over((r[-1], g[-1], b[-1])) rt.set_under((r[0], g[0], b[0])) rt.set_bad(color='k', alpha=0) return rt
def load_planck_cmap(cmap_fname="../misc/Planck_Parchment_RGB.txt"): ''' https://zonca.github.io/2013/09/Planck-CMB-map-at-high-resolution.html ''' from matplotlib.colors import ListedColormap import numpy as np colombi1_cmap = ListedColormap(np.loadtxt(cmap_fname)/255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("white") # color of background, necessary if you want to use cmap = colombi1_cmap return cmap
def make_cmap(rgb): r, g, b = rgb N = 256 vals = np.ones((N, 4)) # vals[:, 0] = np.linspace(r / 256, 1, N) # vals[:, 1] = np.linspace(g / 256, 1, N) i = np.random.randint(0, 2) vals[:, i] = np.linspace(b / 256.0, 1.0, N) map = ListedColormap(vals) rgba = (1 - 0.99, 1 - 0.99, 1 - 0.99) # map.set_over(rgba, alpha=0.0) map.set_under(rgba, alpha=0.0) return map
def fplanckparchmentcmap(): ''' Creates the Planck matplotlib colormap. ''' planck_cmap = ListedColormap( np.loadtxt( "/Users/campbell/Documents/PhD/data/functions/Planck_Parchment_RGB.txt" ) / 255.) planck_cmap.set_bad("gray") # color of missing pixels planck_cmap.set_under( "white" ) # color of background, necessary if you want to use with mollview return planck_cmap
def plot_mwd(RA, Dec, Color, ifFillRect, org=0, title='Mollweide projection', projection='mollweide'): ''' RA, Dec are arrays of the same length. RA takes values in [0,360), Dec in [-90,90], which represent angles in degrees. org is the origin of the plot, 0 or a multiple of 30 degrees in [0,360). title is the title of the figure. projection is the kind of projection: 'mollweide', 'aitoff', 'hammer', 'lambert' ''' x = [np.remainder(n + 360 - org, 360) for n in RA] # shift RA values for i in range(len(x)): if x[i] > 180: x[i] -= 360 # scale conversion to [-180, 180] x[i] = -x[i] # reverse the scale: East to the left colombi1_cmap = ListedColormap(np.loadtxt("CMBColorMap.txt") / 255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under( "white") # color of background, necessary if you want to use tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210]) tick_labels = np.remainder(tick_labels + 360 + org, 360) fig = plt.figure(figsize=(10, 5)) ax = fig.add_subplot(111, projection=projection, facecolor='darkgray') rand = np.random.random_sample((8651, )) ax.scatter(np.radians(x), np.radians(Dec), c=Color, s=1, alpha=1, cmap=colombi1_cmap) # convert degrees to radians #fig.colorbar(ax, orientation='horizontal', fraction=.1) #ax.scatter(0, 0, c='red', s = 10) if ifFillRect: fillRect(x, Dec, Color, 6, 3, ax) ax.set_xticklabels(tick_labels) # we add the scale on the x axis ax.set_title(title) ax.title.set_fontsize(15) ax.set_xlabel("RA") ax.xaxis.label.set_fontsize(12) ax.set_ylabel("Dec") ax.yaxis.label.set_fontsize(12) ax.grid(True) plt.show()
def load_colormap(filename): """Load a colormap defined in a text file filename is the .txt file name located in the data/ path, not the full path. list_available_colormaps() lists the available color tables """ try: colormap = ListedColormap(np.loadtxt(os.path.join(DATA_PATH, filename))/255.) except IOError: print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps())) raise colormap.set_bad("gray") # color of missing pixels colormap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colormap) return colormap
def load_colormap(filename): """Load a colormap defined in a text file filename is the .txt file name located in the data/ path, not the full path. list_available_colormaps() lists the available color tables """ try: colormap = ListedColormap( np.loadtxt(os.path.join(DATA_PATH, filename)) / 255.) except IOError: print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps())) raise colormap.set_bad("gray") # color of missing pixels colormap.set_under( "white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colormap) return colormap
def create_colormap(self, ticks, prec=1e-6): ncolor_p = len(np.where(ticks > prec)[0]) + 1 # including zero ncolor_n = len(np.where(ticks < -prec)[0]) + 1 # including zero colors_interpolated_p = create_colors_interpolated(self._colors_p, ncolor_p) colors_interpolated_n = create_colors_interpolated(self._colors_n, ncolor_n) colors = np.vstack(( colors_interpolated_n, colors_interpolated_p, )) colors = convert_white_to_transparent(colors) print("colors:") print(colors) cmap = ListedColormap(colors[1:-1]) cmap.set_under(colors[ 0]) cmap.set_over (colors[-1]) return cmap
def build_palette4(l1, l2, l3, l4): levs = l1 + l2 + l3 + l4 cm1 = LinearSegmentedColormap.from_list("", ["#000080", "#00b2ee"]) cm2 = LinearSegmentedColormap.from_list("", ["#ffff00", "#ff0000"]) cm3 = LinearSegmentedColormap.from_list("", ["#ff0000", "#bebebe"]) cm4 = LinearSegmentedColormap.from_list("", ["#bebebe", "#ffffff"]) cl1 = cm1(np.linspace(0, 1., len(l1) + 1, endpoint=True)) cl2 = cm2(np.linspace(0, 1., len(l2), endpoint=False)) cl3 = cm3(np.linspace(0, 1., len(l3), endpoint=False)) cl4 = cm4(np.linspace(0, 1., len(l4), endpoint=True)) rgb = np.vstack([cl1, cl2, cl3, cl4]) cmap = ListedColormap(rgb[1:-1], name="Caliop") norm = BoundaryNorm(levs, ncolors=len(levs) - 1, clip=False) cmap.set_under(rgb[0]) cmap.set_over(rgb[-1]) return cmap, norm
def create_colormap(self, ticks, prec=1e-6): ncolor_p = len(np.where(ticks > prec)[0]) + 1 # including zero ncolor_n = len(np.where(ticks < -prec)[0]) + 1 # including zero colors_interpolated_p = create_colors_interpolated( self._colors_p, ncolor_p) colors_interpolated_n = create_colors_interpolated( self._colors_n, ncolor_n) colors = np.vstack(( colors_interpolated_n, colors_interpolated_p, )) colors = convert_white_to_transparent(colors) print("colors:") print(colors) cmap = ListedColormap(colors[1:-1]) cmap.set_under(colors[0]) cmap.set_over(colors[-1]) return cmap
def main(): figure = plt.figure() basemap, lons2d, lats2d = get_basemap_and_coords() lons2d[lons2d > 180] -= 360 x0, y0 = basemap(lons2d, lats2d) dx = x0[1, 0] - x0[0, 0] dy = y0[0, 1] - y0[0, 0] x1 = x0 - dx / 2.0 y1 = y0 - dy / 2.0 permafrost_kind_field = get_permafrost_mask(lons2d, lats2d) cmap = ListedColormap(["r", "b", "y", "c"]) cmap.set_over("w") cmap.set_under("w") # permafrost_kind_field = np.ma.masked_where(permafrost_kind_field == 0, permafrost_kind_field) ax_map = plt.gca() # img = basemap.pcolormesh(x1, y1, permafrost_kind_field, ax = ax_map, vmin = 0.5, vmax = 4.5, cmap = cmap ) permafrost_kind_field = maskoceans(lons2d, lats2d, permafrost_kind_field) img = basemap.contourf(x0, y0, permafrost_kind_field, levels=np.arange(0.5, 5, 0.5), cmap=cmap) divider = make_axes_locatable(ax_map) cax = divider.append_axes("bottom", "5%", pad="3%") cb = plt.colorbar(img, ticks=MultipleLocator(), cax=cax, orientation="horizontal") basemap.contour(x0, y0, permafrost_kind_field, ax=ax_map, levels=list(range(6)), linewidths=0.5, colors="k") basemap.drawcoastlines(ax=ax_map) plt.savefig("test.png") # gdal.Dataset. # TODO: implement pass
def create_colormap_old_2(self, values, prec=1e-6): color_p = self._color_p color_n = self._color_n ncolor_p = len(np.where(values > prec)[0]) ncolor_n = len(np.where(values < -prec)[0]) color_list_0 = np.array([[0.0, 0.0, 0.0, 0.0]]) color_list_n = self.create_color_list(color_n, ncolor_n) color_list_n = color_list_n[::-1] color_list_n = np.vstack((color_list_n, color_list_0)) color_list_p = self.create_color_list(color_p, ncolor_p) color_list_p = np.vstack((color_list_0, color_list_p)) color_list = np.vstack((color_list_n, color_list_p)) color_list = self.convert_white_to_transparent(color_list) print("color_list:") print(color_list) cmap = ListedColormap(color_list[1:-1]) cmap.set_under(color_list[0]) cmap.set_over(color_list[-1]) return cmap
def create_colormap_old_2(self, values, prec=1e-6): color_p = self._color_p color_n = self._color_n ncolor_p = len(np.where(values > prec)[0]) ncolor_n = len(np.where(values < -prec)[0]) color_list_0 = np.array([[0.0, 0.0, 0.0, 0.0]]) color_list_n = self.create_color_list(color_n, ncolor_n) color_list_n = color_list_n[::-1] color_list_n = np.vstack((color_list_n, color_list_0)) color_list_p = self.create_color_list(color_p, ncolor_p) color_list_p = np.vstack((color_list_0, color_list_p)) color_list = np.vstack((color_list_n, color_list_p)) color_list = self.convert_white_to_transparent(color_list) print("color_list:") print(color_list) cmap = ListedColormap(color_list[1:-1]) cmap.set_under(color_list[0]) cmap.set_over(color_list[-1]) return cmap
def main(): """ Plot the data using the row_labels as, you guessed it, row labels and the data_dict as columns. The plot will be saved as input_file.png with the previous extension removed. """ input_file = sys.argv[1] row_labels, data_dict = ParseFile(input_file) # Get the data needed. df = pd.DataFrame(data_dict, index=row_labels) # Create the dataframe. # EDIT THIS TO CHANGE FIGURE SIZE. plt.figure(figsize=(8, 11), dpi=1200) # Set colors [-5 to 5]. Can use html hex codes, recognized html colors, or rgb triplets. colors = ['#8c510a', "#bf812d", "#f5f5f5", "#f5f5f5", "#80cdc1", "#01665e"] cmap = ListedColormap(colors, name="cmap", N=6) # Change N if you have a greater range. # Set colors for over/under the bound limits. cmap.set_over("#003c30") cmap.set_under("#543005") bounds = [-20, -10, -3, 0, 3, 10, 20] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # Create the plot without y axis labels. Change 'extend' to 'both' or 'min' to make cbar extend # in opposite direction. heatmap = sns.heatmap(df, cbar=True, cbar_kws={'extend': 'max'}, cmap=cmap, norm=norm, yticklabels=False) plt.xticks(rotation=90) plt.title(input_file.split(".")[0]) out_name = input_file.split( ".")[0] + ".pdf" # EDIT extension to change output format. heatmap.figure.savefig(out_name)
fh.close() dura1 = np.loadtxt('C:/Users/Yating/Desktop/output/2098-2100Duration_out.txt') dura = np.transpose(dura1) fig = plt.figure(figsize=(4,2)) m = Basemap(projection='merc',llcrnrlon=-78.5079,llcrnrlat=38.00905,urcrnrlon=-75.6454,urcrnrlat=39.91155,resolution='h') ny = dura.shape[0]; nx = dura.shape[1] lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid. x, y = m(lons, lats) mdata = maskoceans(lons, lats, dura) m.drawcoastlines() m.drawcounties(linewidth=0.4) parallels = np.arange(0.,90,0.5) m.drawparallels(parallels,labels=[1,0,0,0],dashes=[2,900],fontsize=10,linewidth=0.4) meridians = np.arange(180.,360.,1) m.drawmeridians(meridians,labels=[0,0,0,1],dashes=[2,900],fontsize=10,linewidth=0.4) cMAP = ListedColormap(['#00bfff','#00ffff','#009933','#33cc33','#c6ff1a','#ffff00', '#ffcc00','#ffcc00','#ffcc00','#ff9933','#ff9933','#ff9933', '#ff8000','#ff8000','#ff8000','#ff6600','#ff6600','#ff6600', '#ff4000','#ff4000','#ff4000']) cMAP.set_under('#0080ff') clevs = np.arange(6,28,1) cs = m.contourf(x, y, mdata, clevs, cmap=cMAP, extend="both") cbar = m.colorbar(cs, "right",size="5%", pad='2%') cbar.set_label('Duration (days/event)') plt.show()
def plotmap(arr, lon, lat, fig_title, pal='anom'): fig_map = plt.figure(figsize=(10, 7)) proj = cart.crs.PlateCarree(central_longitude=0) # -156 ax = plt.axes(projection=proj) if pal == 'anom': pal = [ '#000044', '#0033FF', '#007FFF', '#0099FF', '#00B2FF', '#00CCFF', '#FFFFFF', '#FFCC00', '#FF9900', '#FF7F00', '#FF3300', '#A50000', '#B48C82' ] clevs = [-3., -2.5, -2., -1.5, -1., -0.5, 0.5, 1., 1.5, 2., 2.5, 3.] orient = 'horizontal' shrink = 1. aspect = 35 elif pal == 'diff': pal = ('#0033FF', '#0099FF', '#FFFFFF', '#FFCC00', '#FF3300') clevs = [-1., -0.05, 0.05, 1.] orient = 'horizontal' shrink = 0.45 aspect = 9 else: pal = [ '#D204A9', '#B605C1', '#9406DF', '#7907F7', '#5A45F9', '#368FFB', '#18CDFD', '#00F8E1', '#00E696', '#00D13C', '#0CC600', '#4CD500', '#99E700', '#D8F600', '#FFE900', '#FFB400', '#FF7400', '#FF3F00' ] clevs = list(range(-2, 31, 2)) orient = 'horizontal' shrink = 1. aspect = 35 ccols = ListedColormap(pal[1:-1]) ccols.set_under(pal[0]) ccols.set_over(pal[-1]) norm = BoundaryNorm(clevs, ncolors=ccols.N, clip=False) img = ax.contourf(lon, lat, arr, cmap=ccols, levels=clevs, extend='both', norm=norm, transform=proj) ax.gridlines(crs=proj, linewidth=1.5, color='black', alpha=0.5, linestyle='--', draw_labels=False) parallels = list(range(-180, 181, 40)) meridians = list(range(-90, 91, 20)) ax.set_xticks(parallels, crs=proj) ax.set_yticks(meridians, crs=proj) ax.set_xticklabels(parallels, rotation=0, fontsize=10, fontweight='bold') ax.set_yticklabels(meridians, rotation=0, fontsize=10, fontweight='bold') ax.add_feature( cart.feature.LAND, zorder=50, edgecolor='k', #808080 facecolor='k') ax.set_extent([-180, 180, -80, 80], proj) bar = fig_map.colorbar(img, pad=0.08, spacing='uniform', orientation=orient, extend='both', ax=ax, extendfrac='auto', ticks=clevs, shrink=shrink, aspect=aspect) bar.ax.tick_params(labelsize=11) # fig_map.canvas.flush_events() # ref: https://matplotlib.org/3.1.1/gallery/ticks_and_spines/colorbar_tick_labelling_demo.html # bar.ax.set_yticklabels( # labels=bar.ax.get_yticklabels(), # fontsize=50, weight='bold' # ) bar.set_label(label="(degC)", size=11, weight='bold') ax.set_title(fig_title, fontsize=12, weight='bold', loc='center') return fig_map
def colour_map(colours, match_colour=None, match_value=None, dmin=None, dmax=None, data=None, cmap_len=256, extend='neither'): """ Return a matplotlib colour map from a list of colours. A single colour within the list can be assigned a value by providing the data limits that the colour map will be used on. Note, if using this functionality, match_colour, match_value and data limits (or all the data) must be provided. Args: * colours: list A list of matplotlib accepted colours. These include names (see http://www.w3schools.com/html/html_colornames.asp), html hex colour codes and RGB arrays. Kwargs: * match_colour: string or RBG array Specify one of the colours in the colour list (but not the first or last) to be matched against a given value (see below). * match_value: float Specify a value to which a given colour is to be matched. * dmin: float Data minimum. * dmax: Data maximum * data: array like Alternative to providing the limits. Limits are calculated using the data within the function. * cmap_len: integer Total number of colours in the colour map. * extend: 'neither' or 'both' If 'both', the first and last colours are set to under and over data range colours. Returns: matplotlib.colors.Colormap """ cmap = LinearSegmentedColormap.from_list('cmap', colours, N=cmap_len) if match_colour is not None: assert match_value is not None, 'A value must be given with which to '\ 'match the colour.' colours = [colour.lower() for colour in colours] match_colour = match_colour.lower() assert match_colour in colours, 'The colour to match, %s, is not in'\ ' the given colours list, %s.' % (match_colour, colours) if dmin is None or dmax is None: assert data is not None, 'To scale the colour map, data or data '\ 'minimum and maximum must be provided.' dmin = numpy.min(data) dmax = numpy.max(data) else: assert dmin is not None and dmax is not None, 'Both dmin and dmax'\ ' must be provided.' assert dmin < dmax, 'dmin must be smaller than dmax.' assert dmin <= match_value <= dmax, 'match_value, %s, value must fall'\ ' within the data range, %s & %s.' % (match_value, dmin, dmax) colour_position = float(colours.index(match_colour)) / \ float(len(colours) - 1) if colour_position in [0., 1]: raise UserWarning('The colour to match the value cannot be a '\ 'colour on the limits of the colour map.') value_position = float(match_value - dmin) / \ float(dmax - dmin) if value_position > colour_position: # Cut off the top end of the colour map using equation... x = (colour_position * cmap.N) / value_position # Take colours from 0 to x (+1 for range to reach x value) colour_RGBs = cmap(range(int(round(x + 1)))) cmap = ListedColormap(colour_RGBs) elif value_position < colour_position: # Cut off the bottom end of the colour map using equation... x = ((colour_position - value_position) * cmap.N) / \ (1. - value_position) # Take colours from x to end colour index (+1 for range to reach x # value) colour_RGBs = cmap(range(int(round(x)), (cmap.N + 1))) cmap = ListedColormap(colour_RGBs) else: assert match_value is None, 'A value has been specified without a '\ 'colour to match it with.' if extend == 'both': over_colour = cmap(cmap.N) under_colour = cmap(0) colour_RGBs = cmap(range(1, cmap.N - 1)) cmap = ListedColormap(colour_RGBs) cmap.set_over(over_colour) cmap.set_under(under_colour) return cmap
def main(): # White balanced colors = [(0, 0, 0), (24 , 24 , 112), ( 16 , 78 , 139), ( 23 , 116 , 205), ( 72 , 118 , 255), ( 91 , 172 , 237), ( 173 , 215 , 230), ( 209 , 237 , 237), ( 229 , 239 , 249), ( 242 , 255 , 255), ( 253 , 245 , 230), ( 255 , 228 , 180), ( 243 , 164 , 96), ( 237 , 118 , 0), ( 205 , 102 , 29), ( 224 , 49 , 15), ( 237 , 0 , 0), ( 205 , 0 , 0), ( 139 , 0 , 0)] colors = numpy.array(colors) / 255.0 colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF", "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000", "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00", "#FFFF00", "#7FFF00","#000000"] cmap = ListedColormap(colors[1:]) cmap.set_over(color=colors[-1]) cmap.set_under(color=colors[-1]) #values = numpy.arange(0,10,0.25) #values = [0.01,0.05,0.1,0.25,0.5,0.75,1.0,1.25,1.5,1.75,2.0,2.5,3.0,4.0,5.0,7.5,10.0] values = [0.01,0.10,0.25,0.50,1.0,1.5,2.0,2.5,3.0,4.0,5.0,7.5,10.0,12.5,15.0,17.5,20.0] normer = BoundaryNorm(values, cmap.N, clip=False) ctx = {} nc = netCDF4.Dataset('/mesonet/data/iemre/2012_mw_daily.nc', 'r') lon = nc.variables['lon'][:] lat = nc.variables['lat'][:] ctx['llcrnrlon'] = numpy.min(lon) ctx['llcrnrlat'] = numpy.min(lat) ctx['urcrnrlon'] = numpy.max(lon) ctx['urcrnrlat'] = numpy.max(lat) setup_plot(ctx) idx = iemre.day_idx( mx.DateTime.DateTime(2012,3,1,1,5) ) idx2 = iemre.day_idx( mx.DateTime.DateTime(2012,4,1,1,5) ) tmpk = numpy.ma.array( numpy.sum(nc.variables['p01d'][idx:idx2,:,:],0) ) / 25.4 #nx = int((ctx['map'].xmax-ctx['map'].xmin)/40000.)+1 #ny = int((ctx['map'].ymax-ctx['map'].ymin)/40000.)+1 #rm_tmpk,x,y = ctx['map'].transform_scalar(tmpk,nc.variables['lon'], # nc.variables['lat'],nx,ny, # returnxy=True,masked=True) #print 'Content-Type: text/plain\n' #print numpy.min(rm_tmpk), numpy.max(rm_tmpk) tmpk.mask = numpy.where(tmpk < 0.01, True, False) im = ctx['map'].imshow(tmpk, cmap=cmap,interpolation='nearest',norm=normer,zorder=1) cax = plt.axes([0.932,0.2,0.015,0.6]) clr = ctx['fig'].colorbar(im, cax=cax, format='%g') clr.set_ticks(values) cax.text(-0.75, 0.5, 'Precipitation [inch]', transform=cax.transAxes, size='medium', color='k', horizontalalignment='center', verticalalignment='center', rotation='vertical') ctx['plotax'].text(0.05, -0.05, 'Test test test', ha='left', va='baseline', transform=ctx['plotax'].transAxes) nc.close() print "Content-Type: image/png\n" ctx['fig'].savefig(sys.stdout, format='png', edgecolor='k') """
import healpy as hp import matplotlib.pyplot as plt from glob import glob def GetMapName(freq): indir = '/data/NEVERCOMMIT/' f = np.int(freq) filename = glob('/data/NEVERCOMMIT/*_%d_*fits' % f)[0] return filename ############### Universal colormap # setup linear colormap from matplotlib.colors import ListedColormap planck_freqmap_cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.) planck_freqmap_cmap.set_bad("gray") # color of missing pixels planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use # Graticule spacing in degrees grat_spacing = 10.0 imgsize = 750 imgresolution = 5. faces_to_do = np.arange(32) freq = sys.argv[1] # load a map mapfname = GetMapName(freq) I = hp.ma(hp.read_map(mapfname,field=0,verbose=True)) if np.int(freq)<500: I = I * 1e6 else:
ax.hist(phase_rot.ravel()) ax.set_title( 'Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear' ) # In[112]: plt.close('all') from matplotlib.colors import Normalize from numpy import ma fig, ax = plt.subplots(1, 1, figsize=(12, 12)) colors = sns.color_palette('coolwarm') pal = LinearSegmentedColormap.from_list('test', colors) pal.set_bad('0.75') #75% grey pal.set_over('r') pal.set_under('k') vmin = -5. vmax = 5. ch29 = np.rot90(file_dict['ch29'], 2) ch31 = np.rot90(file_dict['ch31'], 2) the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False) tdiff = ch31 - ch29 tdiff = ma.array(tdiff, mask=np.isnan(tdiff)) CS = ax.imshow(tdiff, cmap=pal, norm=the_norm) cax = plt.colorbar(CS, ax=ax, extend='both') cax.set_label('ch31 - ch29 brightnes temp (K)') ax.set_title('TB 11 micron - TB 8 micron') # ### For next Tuesday: check in a notebook that # # 1. Create a pandas Dataframe with 3 columns: phase, ch29, ch31 using rows
def get_cmap_planck(): """ Function to get Planck colormap https://zonca.github.io/2013/09/Planck-CMB-map-at-high-resolution.html """ cm_data = [[0., 0., 255.], [0., 2., 255.], [0., 5., 255.], [0., 8., 255.], [0., 10., 255.], [0., 13., 255.], [0., 16., 255.], [0., 18., 255.], [0., 21., 255.], [0., 24., 255.], [0., 26., 255.], [0., 29., 255.], [0., 32., 255.], [0., 34., 255.], [0., 37., 255.], [0., 40., 255.], [0., 42., 255.], [0., 45., 255.], [0., 48., 255.], [0., 50., 255.], [0., 53., 255.], [0., 56., 255.], [0., 58., 255.], [0., 61., 255.], [0., 64., 255.], [0., 66., 255.], [0., 69., 255.], [0., 72., 255.], [0., 74., 255.], [0., 77., 255.], [0., 80., 255.], [0., 82., 255.], [0., 85., 255.], [0., 88., 255.], [0., 90., 255.], [0., 93., 255.], [0., 96., 255.], [0., 98., 255.], [0., 101., 255.], [0., 104., 255.], [0., 106., 255.], [0., 109., 255.], [0., 112., 255.], [0., 114., 255.], [0., 117., 255.], [0., 119., 255.], [0., 122., 255.], [0., 124., 255.], [0., 127., 255.], [0., 129., 255.], [0., 132., 255.], [0., 134., 255.], [0., 137., 255.], [0., 139., 255.], [0., 142., 255.], [0., 144., 255.], [0., 147., 255.], [0., 150., 255.], [0., 152., 255.], [0., 155., 255.], [0., 157., 255.], [0., 160., 255.], [0., 162., 255.], [0., 165., 255.], [0., 167., 255.], [0., 170., 255.], [0., 172., 255.], [0., 175., 255.], [0., 177., 255.], [0., 180., 255.], [0., 182., 255.], [0., 185., 255.], [0., 188., 255.], [0., 190., 255.], [0., 193., 255.], [0., 195., 255.], [0., 198., 255.], [0., 200., 255.], [0., 203., 255.], [0., 205., 255.], [0., 208., 255.], [0., 210., 255.], [0., 213., 255.], [0., 215., 255.], [0., 218., 255.], [0., 221., 255.], [6., 221., 254.], [12., 221., 253.], [18., 222., 252.], [24., 222., 251.], [30., 222., 250.], [36., 223., 249.], [42., 223., 248.], [48., 224., 247.], [54., 224., 246.], [60., 224., 245.], [66., 225., 245.], [72., 225., 244.], [78., 225., 243.], [85., 226., 242.], [91., 226., 241.], [97., 227., 240.], [103., 227., 239.], [109., 227., 238.], [115., 228., 237.], [121., 228., 236.], [127., 229., 236.], [133., 229., 235.], [139., 229., 234.], [145., 230., 233.], [151., 230., 232.], [157., 230., 231.], [163., 231., 230.], [170., 231., 229.], [176., 232., 228.], [182., 232., 227.], [188., 232., 226.], [194., 233., 226.], [200., 233., 225.], [206., 233., 224.], [212., 234., 223.], [218., 234., 222.], [224., 235., 221.], [230., 235., 220.], [236., 235., 219.], [242., 236., 218.], [248., 236., 217.], [255., 237., 217.], [255., 235., 211.], [255., 234., 206.], [255., 233., 201.], [255., 231., 196.], [255., 230., 191.], [255., 229., 186.], [255., 227., 181.], [255., 226., 176.], [255., 225., 171.], [255., 223., 166.], [255., 222., 161.], [255., 221., 156.], [255., 219., 151.], [255., 218., 146.], [255., 217., 141.], [255., 215., 136.], [255., 214., 131.], [255., 213., 126.], [255., 211., 121.], [255., 210., 116.], [255., 209., 111.], [255., 207., 105.], [255., 206., 100.], [255., 205., 95.], [255., 203., 90.], [255., 202., 85.], [255., 201., 80.], [255., 199., 75.], [255., 198., 70.], [255., 197., 65.], [255., 195., 60.], [255., 194., 55.], [255., 193., 50.], [255., 191., 45.], [255., 190., 40.], [255., 189., 35.], [255., 187., 30.], [255., 186., 25.], [255., 185., 20.], [255., 183., 15.], [255., 182., 10.], [255., 181., 5.], [255., 180., 0.], [255., 177., 0.], [255., 175., 0.], [255., 172., 0.], [255., 170., 0.], [255., 167., 0.], [255., 165., 0.], [255., 162., 0.], [255., 160., 0.], [255., 157., 0.], [255., 155., 0.], [255., 152., 0.], [255., 150., 0.], [255., 147., 0.], [255., 145., 0.], [255., 142., 0.], [255., 140., 0.], [255., 137., 0.], [255., 135., 0.], [255., 132., 0.], [255., 130., 0.], [255., 127., 0.], [255., 125., 0.], [255., 122., 0.], [255., 120., 0.], [255., 117., 0.], [255., 115., 0.], [255., 112., 0.], [255., 110., 0.], [255., 107., 0.], [255., 105., 0.], [255., 102., 0.], [255., 100., 0.], [255., 97., 0.], [255., 95., 0.], [255., 92., 0.], [255., 90., 0.], [255., 87., 0.], [255., 85., 0.], [255., 82., 0.], [255., 80., 0.], [255., 77., 0.], [255., 75., 0.], [251., 73., 0.], [247., 71., 0.], [244., 69., 0.], [240., 68., 0.], [236., 66., 0.], [233., 64., 0.], [229., 62., 0.], [226., 61., 0.], [222., 59., 0.], [218., 57., 0.], [215., 55., 0.], [211., 54., 0.], [208., 52., 0.], [204., 50., 0.], [200., 48., 0.], [197., 47., 0.], [193., 45., 0.], [190., 43., 0.], [186., 41., 0.], [182., 40., 0.], [179., 38., 0.], [175., 36., 0.], [172., 34., 0.], [168., 33., 0.], [164., 31., 0.], [161., 29., 0.], [157., 27., 0.], [154., 26., 0.], [150., 24., 0.], [146., 22., 0.], [143., 20., 0.], [139., 19., 0.], [136., 17., 0.], [132., 15., 0.], [128., 13., 0.], [125., 12., 0.], [121., 10., 0.], [118., 8., 0.], [114., 6., 0.], [110., 5., 0.], [107., 3., 0.], [103., 1., 0.], [100., 0., 0.]] cmap = ListedColormap(np.array(cm_data) / 255.0, name='planck') # color of missing pixels cmap.set_bad('gray') # color of background, necessary if you want to use cmap.set_under('white') return cmap
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth,**options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels - ``legend_label`` -- the label for this item in the legend EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)) A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase ``plot_points``:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400) To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400) The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200) The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth, alpha, **options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function or a list of boolean functions of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``None``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of ``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``, ``'--'``, ``':'``, ``'-.'``. - ``borderwidth`` -- integer (default: None), the width of the border in pixels - ``alpha`` -- (default: 1) How transparent the fill is. A number between 0 and 1. - ``legend_label`` -- the label for this item in the legend - ``base`` - (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- (default: ``"linear"``) string. The scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Graphics object consisting of 1 graphics primitive Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') Graphics object consisting of 2 graphics primitives An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) Graphics object consisting of 2 graphics primitives A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Graphics object consisting of 1 graphics primitive Since it doesn't look very good, let's increase ``plot_points``:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400) Graphics object consisting of 1 graphics primitive Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) Graphics object consisting of 2 graphics primitives If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Graphics object consisting of 1 graphics primitive Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200) Graphics object consisting of 2 graphics primitives The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) Graphics object consisting of 1 graphics primitive :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) Graphics object consisting of 1 graphics primitive An example of a region plot in 'loglog' scale:: sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog') Graphics object consisting of 1 graphics primitive TESTS: To check that :trac:`16907` is fixed:: sage: x, y = var('x, y') sage: disc1 = region_plot(x^2+y^2 < 1, (x, -1, 1), (y, -1, 1), alpha=0.5) sage: disc2 = region_plot((x-0.7)^2+(y-0.7)^2 < 0.5, (x, -2, 2), (y, -2, 2), incol='red', alpha=0.5) sage: disc1 + disc2 Graphics object consisting of 2 graphics primitives To check that :trac:`18286` is fixed:: sage: x, y = var('x, y') sage: region_plot([x == 0], (x, -1, 1), (y, -1, 1)) Graphics object consisting of 1 graphics primitive sage: region_plot([x^2+y^2==1, x<y], (x, -1, 1), (y, -1, 1)) Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid from sage.symbolic.expression import is_Expression from warnings import warn import numpy if not isinstance(f, (list, tuple)): f = [f] feqs = [equify(g) for g in f if is_Expression(g) and g.operator() is operator.eq and not equify(g).is_zero()] f = [equify(g) for g in f if not (is_Expression(g) and g.operator() is operator.eq)] neqs = len(feqs) if neqs > 1: warn("There are at least 2 equations; If the region is degenerated to points, plotting might show nothing.") feqs = [sum([fn**2 for fn in feqs])] neqs = 1 if neqs and not bordercol: bordercol = incol if not f: return implicit_plot(feqs[0], xrange, yrange, plot_points=plot_points, fill=False, \ linewidth=borderwidth, linestyle=borderstyle, color=bordercol, **options) f_all, ranges = setup_for_eval_on_grid(feqs + f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in f_all[neqs::]],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) if outcol: outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=alpha) else: outcol = rgbcolor('white') cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol, alpha=0) cmap.set_under(incol, alpha=alpha) g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds(Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) if neqs == 0: g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(contours=[-1e-20, 0, 1e-20], cmap=cmap, fill=True, **options))) else: mask = numpy.asarray([[elt > 0 for elt in rows] for rows in xy_data_array], dtype=bool) xy_data_array = numpy.asarray([[f_all[0](x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], dtype=float) xy_data_array[mask] = None if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
else: meta = Metadata(args.infile, startTime=startTime, endTime=endTime) meta.writeMetadata() data = meta.loadData() minVal = np.nanmin(data) maxVal = np.nanmax(data) # Read the colormap PUcols = np.loadtxt(scriptDir + '\\..\\ColorMaps\\' + args.colormap + '.txt') # Create the Color map object gendMap = ListedColormap(PUcols, N=len(PUcols)) # Can't make a color nap with NaN values so we set to them to a value out of the color map data[np.isnan(data)] = minVal - 5 # Set nan values as black gendMap.set_under('black', 1) # Normalize the data and create a ScalarMappable object. # This allows us to efficiently map the values to colors norm = matplotlib.colors.Normalize(vmin=minVal, vmax=maxVal) mapper = cm.ScalarMappable(norm=norm, cmap=gendMap) # Map the data. Take the first 3 columns as last column is alpha colorMappedData = mapper.to_rgba(data, alpha=False, bytes=True)[:, :3] # Save the data to a binary file to minimize size colorMappedData.tofile('colors_' + meta.varNames[0] + '.bin') # See if we need to make an fga file if isVectorized: writeFGAFile(Dataset(args.infile), rad, step)
b = make_tuple(a) a.one # In[40]: plt.close("all") from matplotlib.colors import Normalize from numpy import ma fig, ax = plt.subplots(1, 1, figsize=(12, 12)) colors = sns.color_palette("coolwarm") pal = LinearSegmentedColormap.from_list("test", colors) pal.set_bad("0.75") # 75% grey pal.set_over("r") pal.set_under("k") vmin = -5.0 vmax = 5.0 ch29 = np.rot90(file_dict["ch29"], 2) ch31 = np.rot90(file_dict["ch31"], 2) the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False) tdiff = ch29 - ch31 tdiff = ma.array(tdiff, mask=np.isnan(tdiff)) CS = ax.imshow(tdiff, cmap=pal, norm=the_norm) cax = plt.colorbar(CS, ax=ax, extend="both") cax.set_label("ch29 - ch31 brightnes temp (K)") ax.set_title("TB 8 micron - TB 11 micron") # ### For next Tuesday: check in a notebook that #
( 243 , 164 , 96), ( 237 , 118 , 0), ( 205 , 102 , 29), ( 224 , 49 , 15), ( 237 , 0 , 0), ( 205 , 0 , 0), ( 139 , 0 , 0)] colors = numpy.array(colors) / 255.0 #colors = ["#FFFFFF", "#7FFF00", "#00CD00", "#008B00", "#104E8B", "#1E90FF", # "#00B2EE", "#00EEEE", "#8968CD", "#912CEE", "#8B008B", "#8B0000", # "#CD0000", "#EE4000", "#FF7F00", "#CD8500", "#FFD700", "#EEEE00", # "#FFFF00", "#7FFF00","#000000"] cmap = ListedColormap(colors[:]) cmap.set_over(color=colors[-1]) cmap.set_under(color=colors[0]) normer = BoundaryNorm(values, cmap.N, clip=False) #data_proj,x,y = map.transform_scalar(data,lons,lats,nx,ny,returnxy=True) cax = plt.axes([0.902,0.2,0.03,0.6]) res = map.imshow(data, interpolation='nearest', cmap=cmap, norm=normer, ax=ax) clr = plt.colorbar(res, cax=cax, format='%g') clr.set_ticks(values) map.drawcoastlines(ax=ax) map.drawstates(ax=ax) map.drawcountries(ax=ax) logo = Image.open('NARCCAP.png') ax3 = plt.axes([0.05,0.89,0.2,0.1], frameon=False,
def colour_map(colours, match_colour=None, match_value=None, dmin=None, dmax=None, data=None, cmap_len=256, extend='neither'): """ Return a matplotlib colour map from a list of colours. A single colour within the list can be assigned a value by providing the data limits that the colour map will be used on. Note, if using this functionality, match_colour, match_value and data limits (or all the data) must be provided. Args: * colours: list A list of matplotlib accepted colours. These include names (see http://www.w3schools.com/html/html_colornames.asp), html hex colour codes and RGB arrays. Kwargs: * match_colour: string or RBG array Specify one of the colours in the colour list (but not the first or last) to be matched against a given value (see below). * match_value: float Specify a value to which a given colour is to be matched. * dmin: float Data minimum. * dmax: Data maximum * data: array like Alternative to providing the limits. Limits are calculated using the data within the function. * cmap_len: integer Total number of colours in the colour map. * extend: 'neither' or 'both' If 'both', the first and last colours are set to under and over data range colours. Returns: matplotlib.colors.Colormap """ cmap = LinearSegmentedColormap.from_list('cmap', colours, N=cmap_len) if match_colour is not None: assert match_value is not None, 'A value must be given with which to '\ 'match the colour.' colours = [colour.lower() for colour in colours] match_colour = match_colour.lower() assert match_colour in colours, 'The colour to match, %s, is not in'\ ' the given colours list, %s.' % (match_colour, colours) if dmin is None or dmax is None: assert data is not None, 'To scale the colour map, data or data '\ 'minimum and maximum must be provided.' dmin = numpy.min(data) dmax = numpy.max(data) else: assert dmin is not None and dmax is not None, 'Both dmin and dmax'\ ' must be provided.' assert dmin < dmax, 'dmin must be smaller than dmax.' assert dmin <= match_value <= dmax, 'match_value, %s, value must fall'\ ' within the data range, %s & %s.' % (match_value, dmin, dmax) colour_position = float(colours.index(match_colour)) / \ float(len(colours) - 1) if colour_position in [0., 1]: raise UserWarning('The colour to match the value cannot be a '\ 'colour on the limits of the colour map.') value_position = float(match_value - dmin) / \ float(dmax - dmin) if value_position > colour_position: # Cut off the top end of the colour map using equation... x = (colour_position * cmap.N) / value_position # Take colours from 0 to x (+1 for range to reach x value) colour_RGBs = cmap(range(int(round(x + 1)))) cmap = ListedColormap(colour_RGBs) elif value_position < colour_position: # Cut off the bottom end of the colour map using equation... x = ((colour_position - value_position) * cmap.N) / \ (1. - value_position) # Take colours from x to end colour index (+1 for range to reach x # value) colour_RGBs = cmap(range(int(round(x)), (cmap.N + 1))) cmap = ListedColormap(colour_RGBs) else: assert match_value is None, 'A value has been specified without a '\ 'colour to match it with.' if extend == 'both': over_colour = cmap(cmap.N) under_colour = cmap(0) colour_RGBs = cmap(range(1, cmap.N - 1)) cmap = ListedColormap(colour_RGBs) cmap.set_over(over_colour) cmap.set_under(under_colour) return cmap
def utci_heatmap(df, y_move=-0.22, savepath=None, close=True): series = df.UniversalThermalClimateIndex.to_frame() series = series.rolling(2).mean() colors = [ '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#1A5899', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#347FB9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#82BBD9', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#BFDCEB', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#F7C1AA', '#E3806B', '#E3806B', '#E3806B', '#E3806B', '#E3806B', '#E3806B', '#C84648', '#C84648', '#C84648', '#C84648', '#C84648', '#C84648', '#C84648', '#C84648' ] cmap = ListedColormap(colors) cmap.set_under('#053061') cmap.set_over('#B2182B') bounds = np.arange(-41, 48, 1) norm = BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots(1, 1, figsize=(15, 5)) heatmap = ax.imshow(pd.pivot_table( series, index=series.index.time, columns=series.index.date, values="UniversalThermalClimateIndex").values[::-1], extent=[ dates.date2num(series.index.min()), dates.date2num(series.index.max()), 726449, 726450 ], aspect='auto', cmap=cmap, interpolation='none', vmin=-40, vmax=46) ax.xaxis_date() ax.xaxis.set_major_formatter(dates.DateFormatter('%b')) ax.yaxis_date() ax.yaxis.set_major_formatter(dates.DateFormatter('%H:%M')) ax.invert_yaxis() ax.tick_params(labelleft=True, labelright=True, labelbottom=True) plt.setp(ax.get_xticklabels(), ha='left', color='#555555') plt.setp(ax.get_yticklabels(), color='#555555') [ ax.spines[spine].set_visible(False) for spine in ['top', 'bottom', 'left', 'right'] ] ax.grid(b=True, which='major', color='white', linestyle='--', alpha=0.9) cb = fig.colorbar(heatmap, cmap=cmap, norm=norm, boundaries=bounds, orientation='horizontal', drawedges=False, fraction=0.05, aspect=100, pad=0.1, extend='both', ticks=[-40, -27, -13, 0, 9, 26, 32, 38, 46]) plt.setp(plt.getp(cb.ax.axes, 'xticklabels'), color='#555555') cb.outline.set_visible(False) ax.set_title("UTCI approximation (°C)\n{0:} - {1:} - {2:}".format( df.City[0], df.Country[0], df.StationID[0]), color='#555555', y=1.03) ax.text(0, y_move, 'Extreme\ncold stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(-27 + (-40 - -27) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Very strong\ncold stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(-13 + (-27 - -13) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Strong\ncold stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(0 + (-13 - 0) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Moderate\ncold stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(0 + (9 - 0) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Slight\ncold stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(9 + (26 - 9) / 2, [-44.319, 50.319], [0, 1]), y_move, 'No thermal stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(26 + (32 - 26) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Moderate\nheat stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(32 + (38 - 32) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Strong\nheat stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(np.interp(38 + (46 - 38) / 2, [-44.319, 50.319], [0, 1]), y_move, 'Very strong\nheat stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') ax.text(1, y_move, 'Extreme\nheat stress', ha='center', va='center', transform=ax.transAxes, color='#555555', fontsize='small') plt.tight_layout() # Save figure if savepath != None: print("Saving to {}".format(savepath)) fig.savefig(savepath, bbox_inches="tight", dpi=300, transparent=False) if close: plt.close()
from setup_matplotlib import * import healpy as hp m = hp.ma(hp.read_map("../../data/wmap_band_iqumap_r9_7yr_W_v4.fits", 0)) * 1e3 # muK nside = hp.npix2nside(len(m)) # setup colormap from matplotlib.colors import ListedColormap colombi1_cmap = ListedColormap(np.loadtxt("../../data/parchment1.dat") / 255.0) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under("white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) use_mask = False # using directly matplotlib instead of mollview has higher # quality output, I plan to merge this into healpy # ratio is always 1/2 xsize = 2000 ysize = xsize / 2.0 unit = r"$\mathrm{\mu K}$" # this is the mollview min and max vmin = -1e3 vmax = 1e3 theta = np.linspace(np.pi, 0, ysize) phi = np.linspace(-np.pi, np.pi, xsize)
import numpy as np import healpy as hp import matplotlib.pyplot as plt from scipy import special from matplotlib.colors import ListedColormap #matplotlib.use("agg") colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt") / 255.) colombi1_cmap.set_bad("gray") # color of missing pixels colombi1_cmap.set_under( "white") # color of background, necessary if you want to use # this colormap directly with hp.mollview(m, cmap=colombi1_cmap) cmap_planck = colombi1_cmap import matplotlib matplotlib.use("Agg") Nside = 512 cl = hp.fitsfunc.read_cl("cl.fits") gauss_map = hp.synfast(cl[0], 512, lmax=3 * Nside - 1, fwhm=0, pixwin=True, verbose=False, pol=False) dpi = 800 fig_size_inch = 6, 4.5 fig = plt.figure(1, figsize=(6, 4.5))
def tolnet_colormap(): from matplotlib.colors import ListedColormap from numpy import array Colors = [ array([255, 140, 255]) / 255.0, array([221, 111, 242]) / 255.0, array([187, 82, 229]) / 255.0, array([153, 53, 216]) / 255.0, array([119, 24, 203]) / 255.0, array([0, 0, 187]) / 255.0, array([0, 44, 204]) / 255.0, array([0, 88, 221]) / 255.0, array([0, 132, 238]) / 255.0, array([0, 175, 255]) / 255.0, array([0, 235, 255]) / 255.0, array([39, 255, 215]) / 255.0, array([99, 255, 155]) / 255.0, array([163, 255, 91]) / 255.0, array([211, 255, 43]) / 255.0, array([255, 255, 0]) / 255.0, array([255, 207, 0]) / 255.0, array([255, 159, 0]) / 255.0, array([255, 111, 0]) / 255.0, array([255, 63, 0]) / 255.0, array([255, 0, 0]) / 255.0, array([216, 0, 15]) / 255.0, array([178, 0, 31]) / 255.0, array([140, 0, 47]) / 255.0, array([102, 0, 63]) / 255.0, array([52, 52, 52]) / 255.0, array([96, 96, 96]) / 255.0, array([140, 140, 140]) / 255.0, array([184, 184, 184]) / 255.0, array([228, 228, 228]) / 255.0, [1.0, 1.0, 1.0], ] # Colors = [ # array([255, 140, 255]) / 255., # array([221, 111, 242]) / 255., # array([187, 82, 229]) / 255., # array([153, 53, 216]) / 255., # array([119, 24, 203]) / 255., # array([0, 0, 187]) / 255., # array([0, 44, 204]) / 255., # array([0, 88, 221]) / 255., # array([0, 132, 238]) / 255., # array([0, 175, 255]) / 255., # array([0, 235, 255]) / 255., # array([39, 255, 215]) / 255., # array([99, 255, 155]) / 255., # array([163, 255, 91]) / 255., # array([211, 255, 43]) / 255., # array([255, 255, 0]) / 255., # array([255, 207, 0]) / 255., # array([255, 159, 0]) / 255., # array([255, 111, 0]) / 255., # array([255, 63, 0]) / 255., # array([255, 0, 0]) / 255., # array([216, 0, 15]) / 255., # array([178, 0, 31]) / 255., # array([140, 0, 47]) / 255., # array([102, 0, 63]) / 255., # array([52, 52, 52]) / 255., # array([52, 52, 52]) / 255., # array([52, 52, 52]) / 255., # array([52, 52, 52]) / 255., # array([52, 52, 52]) / 255., # array([52, 52, 52]) / 255., # array([96, 96, 96]) / 255., # array([96, 96, 96]) / 255., # array([96, 96, 96]) / 255., # array([96, 96, 96]) / 255., # array([96, 96, 96]) / 255., # array([96, 96, 96]) / 255. # ] TNcmap = ListedColormap(Colors) TNcmap.set_under([1, 1, 1]) TNcmap.set_over([0, 0, 0]) return TNcmap
def draw_gh_uv_wsp(gh=None, uv=None, wsp=None, map_extent=(50, 150, 0, 65), regrid_shape=20, add_china=True, city=True, south_China_sea=True, output_dir=None, Global=False): plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体) plt.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题) # draw figure plt.figure(figsize=(16, 9)) # set data projection if (Global == True): plotcrs = ccrs.Robinson(central_longitude=115.) else: plotcrs = ccrs.AlbersEqualArea( central_latitude=(map_extent[2] + map_extent[3]) / 2., central_longitude=(map_extent[0] + map_extent[1]) / 2., standard_parallels=[30., 60.]) ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs) plt.title('[' + gh.attrs['model'] + '] ' + str(int(gh['level'].values[0])) + 'hPa 位势高度场, ' + str(int(uv['level'].values[0])) + 'hPa 风场, 风速', loc='left', fontsize=30) datacrs = ccrs.PlateCarree() #adapt to the map ratio map_extent2 = utl.adjust_map_ratio(ax, map_extent=map_extent, datacrs=datacrs) #adapt to the map ratio ax.add_feature(cfeature.OCEAN) utl.add_china_map_2cartopy_public(ax, name='coastline', edgecolor='gray', lw=0.8, zorder=5, alpha=0.5) if add_china: utl.add_china_map_2cartopy_public(ax, name='province', edgecolor='gray', lw=0.5, zorder=5) utl.add_china_map_2cartopy_public(ax, name='nation', edgecolor='black', lw=0.8, zorder=5) utl.add_china_map_2cartopy_public(ax, name='river', edgecolor='#74b9ff', lw=0.8, zorder=5, alpha=0.5) # define return plots plots = {} # draw mean sea level pressure if wsp is not None: x, y = np.meshgrid(wsp['lon'], wsp['lat']) z = np.squeeze(wsp.values) clevs_wsp = [12, 15, 18, 21, 24, 27, 30] colors = [ "#FFF59D", "#FFEE58", "#FFCA28", "#FFC107", "#FF9800", "#FB8C00", '#E64A19', '#BF360C' ] # #RRGGBBAA cmap = ListedColormap(colors, 'wsp') idx_nan = np.where(z < clevs_wsp[0]) z[idx_nan] = np.nan cmap.set_under(color=[1, 1, 1, 0], alpha=0.0) norm = BoundaryNorm(clevs_wsp, ncolors=cmap.N, clip=False) plots['wsp'] = ax.pcolormesh(x, y, z, norm=norm, cmap=cmap, zorder=1, transform=datacrs, alpha=0.5) # draw -hPa wind bards if uv is not None: x, y = np.meshgrid(uv['lon'], uv['lat']) u = np.squeeze(uv['u']) * 2.5 v = np.squeeze(uv['v']) * 2.5 plots['uv'] = ax.barbs(x, y, u.values, v.values, length=6, regrid_shape=regrid_shape, transform=datacrs, fill_empty=False, sizes=dict(emptybarb=0.05), zorder=2) # draw -hPa geopotential height if gh is not None: x, y = np.meshgrid(gh['lon'], gh['lat']) clevs_gh = np.append( np.append( np.arange(0, 480, 4), np.append(np.arange(480, 584, 8), np.arange(580, 604, 4))), np.arange(604, 2000, 8)) plots['gh'] = ax.contour(x, y, np.squeeze(gh['data']), clevs_gh, colors='black', linewidths=2, transform=datacrs, zorder=3) plt.clabel(plots['gh'], inline=1, fontsize=20, fmt='%.0f', colors='black') # grid lines gl = ax.gridlines(crs=datacrs, linewidth=2, color='gray', alpha=0.5, linestyle='--', zorder=4) gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15)) gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15)) utl.add_cartopy_background(ax, name='RD') l, b, w, h = ax.get_position().bounds #forecast information bax = plt.axes([l, b + h - 0.1, .25, .1], facecolor='#FFFFFFCC') bax.set_yticks([]) bax.set_xticks([]) bax.axis([0, 10, 0, 10]) initTime = pd.to_datetime(str( gh.coords['forecast_reference_time'].values)).replace( tzinfo=None).to_pydatetime() fcst_time = initTime + timedelta( hours=gh.coords['forecast_period'].values[0]) #发布时间 if (sys.platform[0:3] == 'lin'): locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8') if (sys.platform[0:3] == 'win'): locale.setlocale(locale.LC_CTYPE, 'chinese') plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15) plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15) plt.text(2.5, 2.5, '预报时效: ' + str(int(gh.coords['forecast_period'].values[0])) + '小时', size=15) plt.text(2.5, 0.5, 'www.nmc.cn', size=15) # add color bar if (wsp is not None): cax = plt.axes([l, b - 0.04, w, .02]) cb = plt.colorbar(plots['wsp'], cax=cax, orientation='horizontal', ticks=clevs_wsp[:], extend='max', extendrect=False) cb.ax.tick_params(labelsize='x-large') cb.set_label('Wind Speed (m/s)', size=20) # add south China sea if south_China_sea: utl.add_south_China_sea(pos=[l + w - 0.091, b, .1, .2]) small_city = False if (map_extent2[1] - map_extent2[0] < 25): small_city = True if city: utl.add_city_on_map(ax, map_extent=map_extent2, transform=datacrs, zorder=110, size=13, small_city=small_city) utl.add_logo_extra_in_axes(pos=[l - 0.02, b + h - 0.1, .1, .1], which='nmc', size='Xlarge') # show figure if (output_dir != None): plt.savefig(output_dir + '高度场_风_预报_' + '起报时间_' + initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' + str(gh.coords['forecast_period'].values[0]) + '小时' + '.png', dpi=200, bbox_inches='tight') if (output_dir == None): plt.show()
numPixelIntp[hh, inCell] += numPixel[hh, cell] numPixelIntp = np.concatenate([numPixelIntp[:, :, 180:], numPixelIntp[:, :, :180]], 2) # define the equal-angle grid lons, lats = np.meshgrid(np.linspace(-179.5, 179.5, 360), np.linspace(-89.5, 89.5, 180)) lonedges, latedges = np.meshgrid(np.linspace(-180, 180, 361), np.linspace(-90, 90, 181)) # set up the plot m = Basemap(projection = 'moll', lon_0 = 0, resolution = 'c') bounds = np.arange(t0 / 2, t1 / 2 + 0.6, 0.5) cmap1 = ListedColormap(('#bbd6e8', '#ffd8b6', '#bfe2bf', '#f2bebe', '#ded1eb', '#dcccc9')) cmap1.set_under('w') cmap1.set_over('w') cols = ('C0', 'C1', 'C2', 'C3', 'C4', 'C5') cmap2 = ListedColormap(cols) plt.figure(figsize = (scol, 0.7 * scol)) mp = m.pcolormesh(lonedges, latedges, UTC, norm = BoundaryNorm(bounds, cmap1.N), cmap = cmap1, latlon = True, rasterized = True) for hhr, col in zip(range(t1 - t0 + 1), cols): m.contour(lons, lats, numPixelIntp[hhr] > 0, 1, colors = col, linewidths = 1, latlon = True) m.drawcoastlines(linewidth = 0.5) m.drawparallels((-60, 60)) cb = ColorbarBase(plt.axes([0.125, 0.1, 0.775, 0.025]), cmap = cmap2, orientation = 'horizontal',
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth, **options): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of ``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``, respectively ``'-'``, ``'--'``, ``':'``, ``'-.'``. - ``borderwidth`` -- integer (default: None), the width of the border in pixels - ``legend_label`` -- the label for this item in the legend - ``base`` - (default: 10) the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- (default: ``"linear"``) string. The scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Graphics object consisting of 1 graphics primitive Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') Graphics object consisting of 2 graphics primitives An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) Graphics object consisting of 2 graphics primitives A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)) Graphics object consisting of 1 graphics primitive A plot with more than one condition (all conditions must be true for the statement to be true):: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Graphics object consisting of 1 graphics primitive Since it doesn't look very good, let's increase ``plot_points``:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive To get plots where only one condition needs to be true, use a function. Using lambda functions, we definitely need the extra ``plot_points``:: sage: region_plot(lambda x,y: x^2+y^2<1 or x<y, (x,-2,2), (y,-2,2), plot_points=400) Graphics object consisting of 1 graphics primitive The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400) Graphics object consisting of 1 graphics primitive Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) Graphics object consisting of 2 graphics primitives If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Graphics object consisting of 1 graphics primitive Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200) Graphics object consisting of 2 graphics primitives The first variable range corresponds to the horizontal axis and the second variable range corresponds to the vertical axis:: sage: s,t=var('s,t') sage: region_plot(s>0,(t,-2,2),(s,-2,2)) Graphics object consisting of 1 graphics primitive :: sage: region_plot(s>0,(s,-2,2),(t,-2,2)) Graphics object consisting of 1 graphics primitive An example of a region plot in 'loglog' scale:: sage: region_plot(x^2+y^2<100, (x,1,10), (y,1,10), scale='loglog') Graphics object consisting of 1 graphics primitive """ from sage.plot.all import Graphics from sage.plot.misc import setup_for_eval_on_grid import numpy if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange, yrange = [r[:2] for r in ranges] xy_data_arrays = numpy.asarray( [[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g], dtype=float) xy_data_array = numpy.abs(xy_data_arrays.prod(axis=0)) # Now we need to set entries to negative iff all # functions were negative at that point. neg_indices = (xy_data_arrays < 0).all(axis=0) xy_data_array[neg_indices] = -xy_data_array[neg_indices] from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() # Reset aspect_ratio to 'automatic' in case scale is 'semilog[xy]'. # Otherwise matplotlib complains. scale = options.get('scale', None) if isinstance(scale, (list, tuple)): scale = scale[0] if scale == 'semilogy' or scale == 'semilogx': options['aspect_ratio'] = 'automatic' g._set_extra_kwds( Graphics._extract_kwds_for_show(options, ignore=['xmin', 'xmax'])) g.add_primitive( ContourPlot( xy_data_array, xrange, yrange, dict(contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **options))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None g.add_primitive( ContourPlot( xy_data_array, xrange, yrange, dict(linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **options))) return g
fig,ax=plt.subplots(1,1) ax.hist(phase_rot.ravel()) ax.set_title('Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear') # In[112]: plt.close('all') from matplotlib.colors import Normalize from numpy import ma fig,ax=plt.subplots(1,1,figsize=(12,12)) colors=sns.color_palette('coolwarm') pal=LinearSegmentedColormap.from_list('test',colors) pal.set_bad('0.75') #75% grey pal.set_over('r') pal.set_under('k') vmin= -5. vmax= 5. ch29 = np.rot90(file_dict['ch29'],2) ch31 = np.rot90(file_dict['ch31'],2) the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False) tdiff= ch31 - ch29 tdiff=ma.array(tdiff,mask=np.isnan(tdiff)) CS= ax.imshow(tdiff,cmap=pal,norm=the_norm) cax=plt.colorbar(CS, ax = ax,extend='both') cax.set_label('ch31 - ch29 brightnes temp (K)') ax.set_title('TB 11 micron - TB 8 micron')