def plot(model, experiment, position, v): folderIN = home + '/TRENDY/S2/' + v + '/bootstrap/' folderlpj = home + '/lpj_guess/runs/global_monthly_CRUNCEP/bootstrap/' fname_cp = 'ensmean_annual_1960-2013_CP_detrend.nc' fname_ep = 'ensmean_annual_1960-2013_EP_detrend.nc' #-- open net-cdf and read in variables if model == 'LPJ-GUESS': if experiment == 'CP': trendy = open_ncfile(folderlpj + v + '_' + fname_cp) else: trendy = open_ncfile(folderlpj + v + '_' + fname_ep) lat = trendy.variables['Lat'][:] lon = trendy.variables['Lon'][:] elif model == 'TRENDY': if experiment == 'CP': trendy = open_ncfile(folderIN + fname_cp) else: trendy = open_ncfile(folderIN + fname_ep) lat = trendy.variables['latitude'][:] lon = trendy.variables['longitude'][:] else: pass var = trendy.variables[v][0, :, :] if v in ('mnee'): var = var * (-1000) else: var = var * 1000 plt.subplot(2, 2, position) #-- create map map = Basemap(projection='cyl', llcrnrlat=-60., urcrnrlat=84., resolution='c', llcrnrlon=0., urcrnrlon=360.) #-- draw coastlines and edge of map map.drawcoastlines(linewidth=0.2) x, y = map(*np.meshgrid(lon, lat)) cut_data = var[:-1, :-1] #-- define the colormap if v in ('resp', 'ter'): cmap = plt.cm.BrBG_r else: cmap = plt.cm.BrBG #-- extract all colors colormap cmaplist = [cmap(i) for i in range(cmap.N)] #-- create the new map cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N) #-- define the bins and normalize levels = np.arange(-28, 32, 4) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) #-- draw filled contours cnplot = map.pcolormesh(x, y, cut_data, cmap=cmap, norm=norm) #-- plot title for subplots plt.title(model + ' ' + experiment, fontsize=12) #-- add colourbar plt.subplots_adjust(top=0.95, left=0.02, right=0.98, bottom=0.11, wspace=0.05, hspace=0.00) cax = plt.axes([0.1, 0.095, 0.8, 0.02]) cbar = fig.colorbar(cnplot, orientation='horizontal', cax=cax) cbar.ax.tick_params(labelsize=10) plt.colorbar(ticks=levels, cax=cax, orientation='horizontal') if v in ('resp', 'ter'): cbar.set_label('Composite anomaly TER [gC]', fontsize=13) elif v in ('dist'): cbar.set_label('Composite anomaly DIST [gC]', fontsize=13) elif v in ('nbp', 'mnee'): cbar.set_label('Composite anomaly NBP [gC]', fontsize=13) elif v in ('mgpp', 'gpp'): cbar.set_label('Composite anomaly GPP [gC]', fontsize=13) else: pass
from matplotlib.colors import ListedColormap, BoundaryNorm import numpy as np from typing import Tuple, Iterable, Optional, Set from enum import Enum from collections import defaultdict CMAP_BATAILLE_ARRAY = [ 'xkcd:azure', # inconnu 'xkcd:white', # vide 'xkcd:violet', # touché 'xkcd:crimson', # coulé ] BATAILLE_CMAP = ListedColormap(CMAP_BATAILLE_ARRAY) BATAILLE_BOUNDS = [0, 1, 2, 3, 4] BATAILLE_NORM = BoundaryNorm(BATAILLE_BOUNDS, BATAILLE_CMAP.N) class InvalidGameState(Exception): pass class InvalidAction(Exception): pass class RetourDeTir(Enum): Vide = 1 Touchee = 2 Coulee = 3 Inconnu = 0
def plot_substrate(): global current_idx, axes_max, cbar # select whichever substrate index you want, e.g., for one model: # 4=tumor cells field, 5=blood vessel density, 6=growth substrate xml_file = "output%08d.xml" % current_idx tree = ET.parse(xml_file) root = tree.getroot() # print('time=' + root.find(".//current_time").text) mins = float(root.find(".//current_time").text) hrs = mins / 60. days = hrs / 24. title_str = '%d days, %d hrs, %d mins' % (int(days), (hrs % 24), mins - (hrs * 60)) # print(title_str) fname = "output%08d_microenvironment0.mat" % current_idx output_dir_str = '.' fullname = output_dir_str + "/" + fname if not pathlib.Path(fullname).is_file(): print("file not found", fullname) return info_dict = {} scipy.io.loadmat(fullname, info_dict) M = info_dict['multiscale_microenvironment'] print('plot_substrate: field_idx=', field_idx) f = M[field_idx, :] # #N = int(math.sqrt(len(M[0,:]))) #grid2D = M[0,:].reshape(N,N) xgrid = M[0, :].reshape(numy, numx) ygrid = M[1, :].reshape(numy, numx) # xvec = grid2D[0,:] #xvec.size #xvec.shape num_contours = 10 num_contours = 90 num_contours = 30 num_contours = 20 # vmin = 30. # vmax = 38. # levels = MaxNLocator(nbins=30).tick_values(vmin, vmax) levels = MaxNLocator(nbins=num_contours).tick_values(vmin, vmax) # cmap = plt.get_cmap('PiYG') cmap = plt.get_cmap('viridis') print('cmap.N = ', cmap.N) norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) # cmap.N = 256 # my_plot = plt.contourf(xvec,xvec,M[field_idx,:].reshape(N,N), num_contours, cmap='viridis') #'viridis' if fix_cmap > 0: # my_plot = plt.contourf(xvec,xvec,M[field_idx,:].reshape(N,N), levels=levels, cmap=cmap) my_plot = plt.contourf(xgrid, ygrid, M[field_idx, :].reshape(numy, numx), levels=levels, extend='both', cmap=cmap) else: # my_plot = plt.contourf(xvec,xvec,M[field_idx,:].reshape(N,N), cmap=cmap) # my_plot = plt.contourf(xgrid, ygrid, M[field_idx, :].reshape(numy, numx), cmap=cmap) my_plot = plt.contourf(xgrid, ygrid, M[field_idx, :].reshape(numy, numx), num_contours, cmap=cmap) if cbar == None: # cbar = plt.colorbar(my_plot, boundaries=np.arange(vmin, vmax, 1.0)) cbar = plt.colorbar(my_plot) else: cbar = plt.colorbar(my_plot, cax=cbar.ax) # plt.axis('equal') plt.title(title_str) # plt.show() png_file = "aaa%08d.png" % current_idx
fig = plt.figure(figsize=(10,10)) ax = plt.axes(xlim=(-100, 900), ylim=(-100, 900)) time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes) last_time_text = ax.text(0.02, 0.90, '', transform=ax.transAxes) ax.set_ylim(ax.get_ylim()[::-1]) for i in range(0, numNodes): x = positionVector[i][0] y = positionVector[i][1] circle = Circle((x, y), 10) ax.add_artist(circle) cmap = ListedColormap(['b', 'r', 'b']) norm = BoundaryNorm([0, 1, 1.5, 2], cmap.N) line = LineCollection([], cmap=cmap, norm=norm,lw=2) ax.add_collection(line) keys = len(lossMatrixHistory) def init(): line.set_segments([]) time_text.set_text('') last_time_text.set_text('') return line, time_text, last_time_text previous_key = 0 def animate(i): global previous_key
def plotter(caller): # inputs: ------------------------------------------------------------------ # caller - marker for whether PyCHAM (0) or tests (2) are the calling module # -------------------------------------------------------------------------- # retrieve useful information from pickle file [sav_name, sch_name, indx_plot, Comp0] = ui.share(1) if (sav_name == 'default_res_name'): print( 'Default results name was used, therefore results not saved and nothing to plot' ) return () dir_path = os.getcwd() # current working directory # obtain just part of the path up to PyCHAM home directory for i in range(len(dir_path)): if dir_path[i:i + 7] == 'PyCHAM': dir_path = dir_path[0:i + 7] break # isolate the scheme name from path to scheme for i in range(len(sch_name) - 1, 0, -1): if sch_name[i] == '/': sch_name = sch_name[i + 1::] break # remove any file formats for i in range(len(sch_name) - 1, 0, -1): if sch_name[i] == '.': sch_name = sch_name[0:i] break dir_path = str(dir_path + '/PyCHAM/output/' + sch_name + '/' + sav_name) # chamber condition --------------------------------------------------------- # retrieve results (num_sb, num_comp, Cfac, yrec, Ndry, rbou_rec, x, timehr, comp_names, _, _, _, y_MV, _, wall_on, space_mode) = retr_out.retr_out(dir_path) # number of actual particle size bins num_asb = num_sb - wall_on if caller == 0: plt.ion() # show results to screen and turn on interactive mode # prepare sub-plots depending on whether particles present if (num_asb) == 0: # no particle size bins if not (indx_plot ): # check whether there are any gaseous components to plot print( 'Please note no initial gas-phase concentrations were received and no particle size bins were present, therefore there is nothing for the standard plot to show' ) return () fig, (ax0) = plt.subplots(1, 1, figsize=(14, 7)) if (num_asb > 0): if not (indx_plot): print( 'Please note, no initial gas-phase concentrations were registered, therefore the gas-phase standard plot will not be shown' ) fig, (ax1) = plt.subplots(1, 1, figsize=(14, 7)) else: fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(14, 7)) par1 = ax1.twinx() # first parasite axis par2 = ax1.twinx() # second parasite axis # Offset the right spine of par2. The ticks and label have already been # placed on the right by twinx above. par2.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, par2 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(par2) # Second, show the right spine. par2.spines["right"].set_visible(True) if (indx_plot): # gas-phase concentration sub-plot --------------------------------------------- for i in range(len(indx_plot)): ax0.semilogy(timehr, yrec[:, indx_plot[i]], '+', linewidth=4.0, label=str(str(Comp0[i]))) ax0.set_ylabel(r'Gas-phase concentration (ppb)', fontsize=14) ax0.set_xlabel(r'Time through simulation (hours)', fontsize=14) ax0.yaxis.set_tick_params(labelsize=14, direction='in') ax0.xaxis.set_tick_params(labelsize=14, direction='in') ax0.legend(fontsize=14) # find maximum and minimum of plotted concentrations for sub-plot label maxy = max(yrec[:, indx_plot].flatten()) miny = min(yrec[:, indx_plot].flatten()) ax0.text(x=timehr[0] - (timehr[-1] - timehr[0]) / 10., y=maxy + ((maxy - miny) / 10.), s='a)', size=14) # end of gas-phase concentration sub-plot --------------------------------------- # particle properties sub-plot -------------------------------------------------- if (num_asb > 0): # if particles present if timehr.ndim == 0: # occurs if only one time step saved Ndry = np.array(Ndry.reshape(1, num_asb)) if num_asb == 1: # just one particle size bin (wall included in num_sb) Ndry = np.array(Ndry.reshape(len(timehr), num_asb)) if timehr.ndim == 0: # occurs if only one time step saved x = np.array(x.reshape(1, num_asb)) if num_asb == 1: # just one particle size bin (wall included in num_sb) x = np.array(x.reshape(len(timehr), num_asb)) if timehr.ndim == 0: # occurs if only one time step saved rbou_rec = np.array(rbou_rec.reshape(1, num_sb)) # plotting number size distribution -------------------------------------- # don't use the first boundary as it's zero, so will error when log10 taken log10D = np.log10(rbou_rec[:, 1::] * 2.0) if (num_asb > 1): # note, can't append zero to start of log10D to cover first size bin as the log10 of the # non-zero boundaries give negative results due to the value being below 1, so instead # assume same log10 distance as the next pair log10D = np.append( (log10D[:, 0] - (log10D[:, 1] - log10D[:, 0])).reshape(-1, 1), log10D, axis=1) # radius distance covered by each size bin (log10(um)) dlog10D = (log10D[:, 1::] - log10D[:, 0:-1]).reshape( log10D.shape[0], log10D.shape[1] - 1) if (num_asb == 1): # single particle size bin # assume lower radius bound is ten times smaller than upper dlog10D = (log10D[:, 0] - np.log10( (rbou_rec[:, 1] / 10.) * 2.)).reshape(log10D.shape[0], 1) # number size distribution contours (/cc (air)) dNdlog10D = np.zeros((Ndry.shape[0], Ndry.shape[1])) dNdlog10D[:, :] = Ndry[:, :] / dlog10D[:, :] # transpose ready for contour plot dNdlog10D = np.transpose(dNdlog10D) # mask the nan values so they're not plotted z = np.ma.masked_where(np.isnan(dNdlog10D), dNdlog10D) # customised colormap (https://www.rapidtables.com/web/color/RGB_Color.html) colors = [(0.60, 0.0, 0.70), (0, 0, 1), (0, 1.0, 1.0), (0, 1.0, 0.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0)] # R -> G -> B n_bin = 100 # Discretizes the colormap interpolation into bins cmap_name = 'my_list' # Create the colormap cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin) # set contour levels levels = (MaxNLocator(nbins=100).tick_values(np.min(z[~np.isnan(z)]), np.max(z[~np.isnan(z)]))) # associate colours and contour levels norm1 = BoundaryNorm(levels, ncolors=cm.N, clip=True) # contour plot with times (hours) along x axis and # particle diameters (nm) along y axis for ti in range(len(timehr) - 1): # loop through times p1 = ax1.pcolormesh(timehr[ti:ti + 2], (rbou_rec[ti, :] * 2 * 1e3), z[:, ti].reshape(-1, 1), cmap=cm, norm=norm1) # if logarithmic spacing of size bins specified, plot vertical axis # logarithmically if space_mode == 'log': ax1.set_yscale("log") ax1.set_ylabel('Diameter (nm)', size=14) ax1.xaxis.set_tick_params(labelsize=14, direction='in') ax1.yaxis.set_tick_params(labelsize=14, direction='in') # label according to whether gas-phase plot also displayed if (indx_plot): ax1.text(x=timehr[0] - (timehr[-1] - timehr[0]) / 11., y=np.amax(rbou_rec * 2 * 1e3) * 1.05, s='b)', size=14) else: ax1.text(x=timehr[0] - (timehr[-1] - timehr[0]) / 11., y=np.amax(rbou_rec * 2 * 1e3) * 1.3, s='a)', size=14) ax1.set_xlabel(r'Time through simulation (hours)', fontsize=14) cb = plt.colorbar(p1, format=ticker.FuncFormatter(fmt), pad=0.25) cb.ax.tick_params(labelsize=14) # colour bar label cb.set_label('dN/dlog10(D) $\mathrm{(cm^{-3})}$', size=14, rotation=270, labelpad=20) # ---------------------------------------------------------------------------------------- # total particle number concentration #/cm3 # include total number concentration (# particles/cc (air)) on contour plot # first identify size bins with radius exceeding 3nm # empty array for holding total number of particles Nvs_time = np.zeros((Ndry.shape[0])) for i in range(num_asb): # size bin loop # get the times when bin exceeds 3nm - might be wanted to deal with particle counter detection limits # ish = x[:, i]>3.0e-3 # Nvs_time[ish] += Ndry[ish, i] # sum number Nvs_time[:] += Ndry[:, i] # sum number p3, = par1.plot(timehr, Nvs_time, '+k', label='N') par1.set_ylabel('N (# $\mathrm{cm^{-3})}$', size=14, rotation=270, labelpad=20) # vertical axis label par1.yaxis.set_major_formatter(ticker.FormatStrFormatter( '%.0e')) # set tick format for vertical axis par1.yaxis.set_tick_params(labelsize=14) # SOA mass concentration --------------------------------------------------------------- # array for SOA sum with time SOAvst = np.zeros((1, len(timehr))) final_i = 0 # check whether water and/or core is present if comp_names[-2] == 'H2O': # if both present final_i = 2 if comp_names[-1] == 'H2O': # if just water final_i = 1 # note that the seed component is only registered in init_conc_func if initial # particle concentration (pconc) exceeds zero, therefore particle-phase material # must be present at start of experiment (row 0 in y) if final_i == 0 and y[0, num_speci:(num_speci * (num_asb + 1))].sum() > 1.0e-10: final_i = 1 for i in range(num_asb): # particle size bin loop # sum of organics in condensed-phase at end of simulation (ug/m3 (air)) # to replicate the SMPS results, find the volume of particles then # assume a density of 1.0 g/cm3 SOAvst[0, :] += np.sum( (yrec[:, ((i + 1) * num_comp):((i + 2) * num_comp - final_i)] / si.N_A * (y_MV[0:-final_i]) * 1.0e12), axis=1) # log10 of maximum in SOA if (max(SOAvst[0, :]) > 0): SOAmax = int(np.log10(max(SOAvst[0, :]))) else: SOAmax = 0. # transform SOA so no standard notation required SOAvst[0, :] = SOAvst[0, :] p5, = par2.plot(timehr, SOAvst[0, :], 'xk', label='[secondary]') par2.set_ylabel(str('[secondary] ($\mathrm{\mu g\, m^{-3}})$'), rotation=270, size=16, labelpad=25) # set label, tick font and [SOA] vertical axis to red to match scatter plot presentation par2.yaxis.label.set_color('black') par2.tick_params(axis='y', colors='black') par2.spines['right'].set_color('black') par2.yaxis.set_major_formatter(ticker.FormatStrFormatter( '%.0e')) # set tick format for vertical axis par2.yaxis.set_tick_params(labelsize=16) par2.text((timehr)[0], max(SOAvst[0, :]) / 2.0, 'assumed particle density = 1.0 $\mathrm{g\, cm^{-3}}$') plt.legend(fontsize=14, handles=[p3, p5], loc=4) # end of particle properties sub-plot ----------------------------------- # save and display plt.savefig(str(dir_path + '/' + sav_name + '_output_plot.png')) if caller == 2: plt.show() return ()
def plot_comparisons_of_seasonal_sst_with_homa_obs(self, start_year=None, end_year=None, season_to_months=None, exp_label=""): model_data = self.get_seasonal_mean_lst( season_to_months=season_to_months, start_year=start_year, end_year=end_year) obs_sst_path = os.path.expanduser( "~/skynet3_rech1/nemo_obs_for_validation/GreatLakes_2003_5km-2/sst-glk.nc" ) obs_data = self.read_and_interpolate_homa_data( path=obs_sst_path, start_year=start_year, end_year=end_year, season_to_months=season_to_months) plot_utils.apply_plot_params(font_size=10, width_pt=None, width_cm=20, height_cm=10) # calculate climatologic differences diff = {} for season in list(season_to_months.keys()): diff[season] = np.mean([ model_data[y][season] - obs_data[y][season] for y in range(start_year, end_year + 1) ], axis=0) diff[season] = np.ma.masked_where(~self.lake_mask, diff[season]) the_field = diff[season] print("diff stats({}): min={}; max={}; avg={}".format( season, the_field.min(), the_field.max(), the_field.mean())) # plot seasonal biases xx, yy = self.basemap(self.lons.copy(), self.lats.copy()) # calculate difference ranges diff_max = 0 for season, the_diff in diff.items(): diff_max = max(np.percentile(np.abs(the_diff[~the_diff.mask]), 90), diff_max) diff_max = 5 locator = MaxNLocator(nbins=12, symmetric=True) bounds = locator.tick_values(-diff_max, diff_max) bn = BoundaryNorm(bounds, len(bounds) - 1) cmap = cm.get_cmap("RdBu_r", len(bounds) - 1) im = None fig = plt.figure() ncols = 2 # fig.suptitle(r"LST $\left({\rm ^\circ C}\right)$", font_properties=FontProperties(weight="bold")) gs = GridSpec(len(season_to_months) // ncols, ncols + 1, width_ratios=[ 1.0, ] * ncols + [ 0.05, ]) for i, season in enumerate(season_to_months.keys()): ax = fig.add_subplot(gs[i // ncols, i % ncols]) im = self.basemap.pcolormesh(xx, yy, diff[season][:], ax=ax, cmap=cmap, norm=bn) ax.set_title(season) self.basemap.drawcoastlines(ax=ax, linewidth=0.5) if not i: ax.set_ylabel("NEMO - Obs") cb = plt.colorbar(im, ticks=locator, cax=fig.add_subplot(gs[:, -1]), extend="both") nemo_img_dir = "nemo" if not os.path.isdir(nemo_img_dir): os.mkdir(nemo_img_dir) plt.tight_layout() fig.savefig( os.path.join(nemo_img_dir, "sst_homa_validation_{}.pdf".format(exp_label))) plt.show()
@author: DaniJ """ import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib.colors import ListedColormap, BoundaryNorm x = np.linspace(0, 3 * np.pi, 500) y = np.sin(x) z = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative # Create a colormap for red, green and blue and a norm to color # f' < -0.5 red, f' > 0.5 blue, and the rest green cmap = ListedColormap(['r', 'g', 'b']) norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N) # Create a set of line segments so that we can color them individually # This creates the points as a N x 1 x 2 array so that we can stack points # together easily to get the segments. The segments array for line collection # needs to be numlines x points per line x 2 (x and y) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # Create the line collection object, setting the colormapping parameters. # Have to set the actual values used for colormapping separately. lc = LineCollection(segments, cmap=cmap, norm=norm) lc.set_array(z) lc.set_linewidth(3) fig1 = plt.figure()
def plot_vcs(self, ax, start_xy, end_xy, field_name, cmap=None, min_max=None, cmap_bins=None, cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ :param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots :param start_xy: (start_x, start_y) units:km, VCS start position! :param end_xy: (end_x, end_y) units:km, VCS end position! :param field_name: field dict to select data, eg: "dBZ" "V" :param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins: bins of colormap :param cbar: bool, if True, plot with colorbar, :param orientation: vertical or horizontal, it is vaild when cbar is True :param cbar_ticks: Set the locations of the tick marks from sequence ticks :param cbar_ticklabels: Set the text values of the tick labels. :return: """ assert isinstance(ax, matplotlib.axes._axes.Axes ), "axes should be matplotlib axes not cartopy axes!" if field_name == "V": vmax = self.Radar.scan_info.nyquist_velocity[0].values vmin = -1 * vmax elif min_max is not None: vmin, vmax = min_max elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1: vmax = np.nanmax(self.Radar.fields[0][field_name]) vmin = np.nanmin(self.Radar.fields[0][field_name]) else: vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]] if cmap is None: cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]] if cmap_bins is None: cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]] start_point = (start_xy[0] * 1000., start_xy[1] * 1000) ##km to meters end_point = (end_xy[0] * 1000., end_xy[1] * 1000) ##km to meters mesh_xy, mesh_z, field_data = self.Radar.get_vcs_data( start_point, end_point, field_name) cmaps = plt.get_cmap(cmap) levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax) norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True) for isweep, _ in enumerate(mesh_xy): gci = ax.pcolormesh(mesh_xy[isweep] / 1000., mesh_z[isweep] / 1000., field_data[isweep], cmap=cmaps, norm=norm, **kwargs) if cbar: cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = levels else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return gci
def plot_lonlat_map(ax, lon, lat, data, transform, extend=None, cmap="CN_ref", bounds=np.arange(-5, 76, 5), cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ :param ax:cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree()) :param lon: lon mesh grid for data units: degree :param lat: lat mesh grid for data units: degree :param data: radar data ,dims like lat, lon :param transform: The transform argument to plotting functions tells Cartopy what coordinate system your data are defined in. :param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees :param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins:bins of cmaps, int :param cbar: bool, if True, plot with colorbar, :param orientation: vertical or horizontal, it is vaild when cbar is True :param kwargs: kwargs: other arguments for pcolormesh! :return: pcolor result """ assert isinstance( ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!" if extend is None: min_lon = np.min(lon) max_lon = np.max(lon) min_lat = np.min(lat) max_lat = np.max(lat) else: min_lon, max_lon, min_lat, max_lat = extend ax.set_aspect("equal") cmaps = plt.get_cmap(cmap) norm = BoundaryNorm(bounds, ncolors=cmaps.N, clip=True) pm = ax.pcolormesh(lon, lat, data, transform=transform, cmap=cmap, norm=norm, zorder=4, **kwargs) ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \ edgecolor='none', facecolor="white"), zorder=1) ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2) ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3) ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), transform, \ edgecolor='k', facecolor='none'), linewidth=0.5, \ linestyle='-', zorder=5, alpha=0.8) parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1) meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1) ax.set_xticks(meridians, crs=transform) ax.set_yticks(parallels, crs=transform) lon_formatter = LongitudeFormatter() lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) if cbar: cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = bounds else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return pm
def plot_crf_map(self, ax, extend=None, cmap=CINRAD_COLORMAP[CINRAD_field_mapping['dBZ']], min_max=CINRAD_field_normvar[CINRAD_field_mapping['dBZ']], cmap_bins=CINRAD_field_bins[CINRAD_field_mapping['dBZ']], cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ 显示组合反射率因子 :param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree()) :param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees :param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins:bins of cmaps, int :param cbar: bool, if True, plot with colorbar, :param orientation: vertical or horizontal, it is vaild when cbar is True :param cbar_ticks: Set the locations of the tick marks from sequence ticks :param cbar_ticklabels: Set the text values of the tick labels. :param kwargs: kwargs: other arguments for pcolormesh! :return: """ assert isinstance( ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!" vmin, vmax = min_max if extend is None: min_lon = np.min(self.Radar.fields[0].lon) max_lon = np.max(self.Radar.fields[0].lon) min_lat = np.min(self.Radar.fields[0].lat) max_lat = np.max(self.Radar.fields[0].lat) else: min_lon, max_lon, min_lat, max_lat = extend XLON = np.arange(min_lon, max_lon, 0.01) YLAT = np.arange(min_lat, max_lat, 0.01) #ax.set_aspect("equal") self.Radar.add_product_CR_lonlat(XLON, YLAT) radar_data = self.Radar.product["CR_geo"].values lon, lat = np.meshgrid(XLON, YLAT, indexing="ij") cmaps = plt.get_cmap(cmap) levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax) norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True) pm = ax.pcolormesh(lon, lat, radar_data, transform=self.transform, cmap=cmap, norm=norm, zorder=4, **kwargs) #ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=self.transform) ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \ edgecolor='none', facecolor="white"), zorder=1) ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2) ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3) ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), self.transform, \ edgecolor='k', facecolor='none'), linewidth=0.5, \ linestyle='-', zorder=5, alpha=0.8) parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1) meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1) ax.set_xticks(meridians, crs=self.transform) ax.set_yticks(parallels, crs=self.transform) lon_formatter = LongitudeFormatter() lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) if cbar: cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = levels else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return ax
def plot_vcs_map(self, ax, start_lonlat, end_lonlat, field_name, cmap=None, min_max=None,\ cmap_bins=None, cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ :param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots :param start_lonlat:(startlon, startlat), VCS start position! :param end_lonlat:(endlon, endlat), VCS end position! :param field_name: field dict to select data, eg: "dBZ" "V" :param cmap:str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max:The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins:bins of cmaps, int :param cbar:bool, if True, plot with colorbar, :param orientation:vertical or horizontal, it is vaild when cbar is True :param cbar_ticks: Set the locations of the tick marks from sequence ticks :param cbar_ticklabels: Set the text values of the tick labels. :param kwargs: other arguments for pcolormesh! :return: """ assert isinstance(ax, matplotlib.axes._axes.Axes ), "axes should be matplotlib axes not cartopy axes!" if field_name == "V": vmax = self.Radar.scan_info.nyquist_velocity[0].values vmin = -1 * vmax elif min_max is not None: vmin, vmax = min_max elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1: vmax = np.nanmax(self.Radar.fields[0][field_name]) vmin = np.nanmin(self.Radar.fields[0][field_name]) else: vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]] if cmap is None: cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]] if cmap_bins is None: cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]] cmaps = plt.get_cmap(cmap) levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax) norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True) start_x, start_y = geographic_to_cartesian_aeqd( lat=start_lonlat[1], lon=start_lonlat[0], lat_0=self.Radar.scan_info.latitude.values, lon_0=self.Radar.scan_info.longitude.values) end_x, end_y = geographic_to_cartesian_aeqd( lat=end_lonlat[1], lon=end_lonlat[0], lat_0=self.Radar.scan_info.latitude.values, lon_0=self.Radar.scan_info.longitude.values) mesh_xy, mesh_z, field_data = self.Radar.get_vcs_data( (start_x[0], start_y[0]), (end_x[0], end_y[0]), field_name) for isweep, _ in enumerate(mesh_xy): gci = ax.pcolormesh(mesh_xy[isweep] / 1000., mesh_z[isweep] / 1000., field_data[isweep], cmap=cmaps, norm=norm, **kwargs) xticks_data = ax.get_xticks() x_points_tk, y_points_tk = VerticalSection.get_points_from_ranges( (start_x[0] / 1000., start_y[0] / 1000), (end_x[0] / 1000, end_y[0] / 1000), xticks_data) lon_point, lat_point = cartesian_to_geographic_aeqd( x_points_tk * 1000., y_points_tk * 1000., lat_0=self.Radar.scan_info.latitude.values, lon_0=self.Radar.scan_info.longitude.values) # to meters ax.set_xticklabels(["(%.2f, %.2f)" % (lon_point[i], lat_point[i]) \ for i, _ in enumerate(xticks_data)], rotation=15, fontsize=10) if cbar: cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = levels else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return gci
def plot_ppi_map(self, ax, sweep_num, field_name, extend=None, cmap=None, min_max=None,\ cmap_bins=None, cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ :param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree()) :param sweep_num: The sweep_num volume scan to draw, from 0 start! :param field_name: field dict to select data, eg: "dBZ" "V" :param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees :param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins:bins of cmaps, int :param cbar: bool, if True, plot with colorbar, :param orientation: vertical or horizontal, it is vaild when cbar is True :param cbar_ticks: Set the locations of the tick marks from sequence ticks :param cbar_ticklabels: Set the text values of the tick labels. :param kwargs: kwargs: other arguments for pcolormesh! :return: """ assert isinstance( ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!" if field_name == "V": vmax = self.Radar.scan_info.nyquist_velocity[sweep_num].values vmin = -1 * vmax elif min_max is not None: vmin, vmax = min_max elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1: vmax = np.nanmax(self.Radar.fields[sweep_num][field_name]) vmin = np.nanmin(self.Radar.fields[sweep_num][field_name]) else: vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]] if cmap is None: cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]] if cmap_bins is None: cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]] if extend is None: min_lon = np.min(self.Radar.fields[sweep_num].lon) max_lon = np.max(self.Radar.fields[sweep_num].lon) min_lat = np.min(self.Radar.fields[sweep_num].lat) max_lat = np.max(self.Radar.fields[sweep_num].lat) else: min_lon, max_lon, min_lat, max_lat = extend #ax.set_aspect("equal") radar_data = self.Radar.fields[sweep_num][field_name] lat, lon = radar_data.lat, radar_data.lon cmaps = plt.get_cmap(cmap) levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax) norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True) pm = ax.pcolormesh(lon, lat, radar_data, transform=self.transform, cmap=cmap, norm=norm, zorder=4, **kwargs) ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0) ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \ edgecolor='none', facecolor="white"), zorder=1) ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2) ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3) ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), self.transform, \ edgecolor='k', facecolor='none'), linewidth=0.5, \ linestyle='-', zorder=5, alpha=0.8) parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1) meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1) ax.set_xticks(meridians, crs=self.transform) ax.set_yticks(parallels, crs=self.transform) lon_formatter = LongitudeFormatter() lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter) if cbar: cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = levels else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return ax
def plot_ppi(self, ax, sweep_num, field_name, cmap=None, min_max=None, cmap_bins=None, cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs): """ :param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots :param sweep_num: The sweep_num volume scan to draw, from 0 start! :param field_name: field dict to select data, eg: "dBZ" "V" :param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py! :param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data! :param cmap_bins: bins of colormaps :param cbar: if True, plot with colorbar, else not! :param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention! :param cbar_ticks: Set the locations of the tick marks from sequence ticks :param cbar_ticklabels: Set the text values of the tick labels. :param kwargs: other arguments for pcolormesh! :return: """ assert isinstance(ax, matplotlib.axes._axes.Axes ), "axes should be matplotlib axes not cartopy axes!" if field_name == "V": vmax = self.Radar.scan_info.nyquist_velocity[sweep_num].values vmin = -1 * vmax elif min_max is not None: vmin, vmax = min_max elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1: vmax = np.nanmax(self.Radar.fields[sweep_num][field_name]) vmin = np.nanmin(self.Radar.fields[sweep_num][field_name]) else: vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]] if cmap is None: cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]] if cmap_bins is None: cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]] ax.set_aspect("equal") radar_data = self.Radar.fields[sweep_num][field_name] x, y = radar_data.x, radar_data.y cmaps = plt.get_cmap(cmap) levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax) norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True) gci = ax.pcolormesh(x / 1000., y / 1000., radar_data, cmap=cmaps, \ zorder=0, norm=norm, **kwargs) if cbar: cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation) if cbar_ticks is None: ticks = levels else: ticks = cbar_ticks cb.set_ticks(ticks) if cbar_ticklabels is not None: if orientation == "vertical": cb.ax.set_yticklabels(cbar_ticklabels) else: cb.ax.set_xticklabels(cbar_ticklabels) return gci
def draw(traject): """calculates size of grid""" xsize = int(syn_period // unit + 1) ysize = int(ttcutoff // unit + 1) """mapping orbits result to specific grid-point.""" Z = np.zeros(shape=(xsize, ysize), dtype=float) cman = np.zeros( shape=(xsize, ysize), dtype=int) # N used to calculate cumulative moving average for traj in traject: sa_rad = traj[0] dv1 = traj[1] dv2 = traj[2] time_s = traj[3] sa_t = sa_rad * syn_period / (2 * pi) """calculates the corresponding point""" x = int(sa_t // unit) y = int(time_s // unit) """cutoffs""" tdv = (dv1 + dv2) / dv_unit if cman[x, y] == 0: Z[x, y] = tdv else: """rolling average in the computation of dv required""" Z[x, y] += (tdv - Z[x, y]) / (cman[x, y] + 1 + 1) # Z[x, y] = min(Z[x, y], tdv) """increment the rolling count by 1""" cman[x, y] = cman[x, y] + 1 fig = plt.figure() """enumerate to find peak and bottom of chart""" zmax = Z.max() zmin = zmax for indexz, z in np.ndenumerate(Z): if z != 0: if z < zmin: zmin = z """initialize plot with 1 subplot""" ax1 = fig.add_subplot(111) ax1.title.set_text("dV Variation During 1 Synodic Period") ax1.set_ylim(top=ysize) """black magic happens here""" levels = MaxNLocator(nbins=8).tick_values(zmin, zmax) cmap = plt.get_cmap("hot") norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) sigmadv = ax1.pcolormesh(np.swapaxes(Z, 0, 1), norm=norm, cmap=cmap) plt.colorbar(sigmadv) ax1.set_ylabel("Travel Time / x {} days".format( round(unit / 86400), 1)) """plot isochorno line""" for i in range(0, xsize, 10): ax1.plot([0, i], [i, 0], linewidth=0.25, color="white", linestyle="dashed") plt.show()
############################################################ # pnum=10 #len(pname) #print np.shape(sfcelv_hydroweb) colors=['xkcd:pastel blue','xkcd:teal','xkcd:aqua green','xkcd:dark pink','xkcd:purple','xkcd:magenta'] labels=["cmf oroginal","cmf interpolated","cmf ele diff",TAG] #============================= vmin=1.0 vmax=26.0 norm=Normalize(vmin=vmin,vmax=vmax) bounds=np.arange(-0.5,26,1.0) ############################################################ cmapL = matplotlib.colors.ListedColormap(['w','w','grey','k','w','k','w','y','w','w','blue','w','w','w','w','w','w','w','w','w','red', 'w','w','w','w','red']) cmapL.set_under("none") #"#000000",alpha=0) cmapL.set_over("none") cmapL.colorbar_extend="neither" norml=BoundaryNorm(bounds,cmapL.N) #len(bounds)-1) ############################################################ nums=[] river=[] pname=[] lons =[] lats =[] xlist=[] ylist=[] leled=[] egm08=[] egm96=[] llsat=[] ldtom=[] lflag=[] kx1lt=[]
m = Basemap(llcrnrlon=lon1, llcrnrlat=lat2, urcrnrlon=lon2, urcrnrlat=lat1, projection='mill', resolution='l') #m.fillcontinents(color='white') m.drawcoastlines(linewidth=0.4, color='k') m.drawcountries(linewidth=0.4, color='k') cmap = 'OrRd' cmap = plt.get_cmap(cmap) colors = cmap(np.linspace(0.1, 1, cmap.N)) cmap2 = LinearSegmentedColormap.from_list(cmap, colors) bounds=np.linspace(0,2000,21) norm = BoundaryNorm(bounds, ncolors=cmap2.N, clip=True) x,y = m(obs_lons_mjo, obs_lats_mjo) im = m.contourf(x,y,track_error_mjo, cmap=cmap2, levels=bounds, tri=True, extend="max") m.scatter(x,y,c='navy',s=0.2) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, extend="max", ticks=bounds[0::2]) # cbar.ax.set_yticklabels([int(i) for i in bounds[0::2]]) cbar.ax.tick_params(labelsize=14) # colorbar font size plt.text(0.01, 0.04, 'MJO Phase '+str(MJO)+'\nTrack Errors (km)\n'+str(lt)+' Days Ahead', transform=ax.transAxes, fontsize=12) #plt.savefig('ukmo_'+fcst_type+'.spatial_track_errors_map.MJO_'+str(MJO)+'.lead_time_'+str(lt)+'.2010-2020.contour_with_dots.png', bbox_inches='tight', dpi=400)
def plt_tsk(nc, model, figname, lease_areas=None): """ Create a pcolor surface map of surface skin temperature with contours :param nc: netcdf file :param model: the model version that is being plotted, e.g. 3km or 9km :param figname: full file path to save directory and save filename :param lease_areas: optional dictionary containing lat/lon coordinates for wind energy lease area polygon """ lease_areas = lease_areas or None tsk = nc['TSK'] color_label = 'Surface Skin Temperature ($^\circ$C)' plot_types = ['full_grid', 'bight'] # plot the full grid and just NY Bight area for pt in plot_types: if pt == 'full_grid': # subset the entire grid tsk_sub, ax_lims, xticks, yticks = cf.subset_grid(tsk, model) else: # subset just NY Bight new_fname = 'bight_{}'.format(figname.split('/')[-1]) figname = '/{}/{}'.format(os.path.join(*figname.split('/')[0:-1]), new_fname) tsk_sub, ax_lims, xticks, yticks = cf.subset_grid(tsk, 'bight') fig, ax, lat, lon = cf.set_map(tsk_sub) # add text to the bottom of the plot cf.add_text(ax, nc.SIMULATION_START_DATE, nc.time_coverage_start, model) # initialize keyword arguments for map features kwargs = dict() kwargs['xticks'] = xticks kwargs['yticks'] = yticks cf.add_map_features(ax, ax_lims, **kwargs) if lease_areas: pf.add_lease_area_polygon(ax, lease_areas, 'magenta') # convert degrees K to F #d = np.squeeze(tsk_sub.values) * 9/5 - 459.67 # convert degrees K to C d = np.squeeze(tsk_sub.values) - 273.15 # add contour lines contour_list = np.linspace(0, 30, 7) pf.add_contours(ax, lon, lat, d, contour_list) # plot data # pcolormesh: coarser resolution, shows the actual resolution of the model data # vlims = [-20, 110] # cmap = plt.get_cmap('jet') # levels = MaxNLocator(nbins=30).tick_values(vlims[0], vlims[1]) # levels every 5 degrees F # levels = MaxNLocator(nbins=65).tick_values(vlims[0], vlims[1]) # levels every 2 degrees F vlims = [0, 32] cmap = cmo.cm.thermal levels = MaxNLocator(nbins=16).tick_values(vlims[0], vlims[1]) # levels every 2 degrees C norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) kwargs = dict() kwargs['ttl'] = color_label kwargs['clab'] = color_label # kwargs['var_lims'] = vlims kwargs['norm_clevs'] = norm kwargs['extend'] = 'both' kwargs['cmap'] = cmap pf.plot_pcolormesh(fig, ax, lon, lat, d, **kwargs) # # contourf: smooths the resolution of the model data, plots are less pixelated # kwargs = dict() # kwargs['ttl'] = '2m {}'.format(color_label) # kwargs['clab'] = color_label # kwargs['var_lims'] = [-20, 110] # kwargs['cbar_ticks'] = np.linspace(-20, 100, 7) # # levels = np.arange(-20, 110.5, .5) # pf.plot_contourf(fig, ax, lon, lat, d, levels, **kwargs) plt.savefig(figname, dpi=200) plt.close()
def show_domain(grid_config, halo=None, blending=None, draw_rivers=True, grdc_basins_of_interest=None, directions_file=None, imgfile_prefix="bc-mh", include_buffer=True, ax=None, basin_border_width=1.5, path_to_shape_with_focus_polygons=None, nc_varname_to_show="accumulation_area", clevels=None, draw_colorbar=True): assert isinstance(grid_config, GridConfig) is_subplot = ax is not None data_mask = None fig = None if not is_subplot: fig = plt.figure() ax = plt.gca() halo = 10 if halo is None else halo blending = 10 if blending is None else blending if include_buffer: bmp = grid_config.get_basemap(resolution="l") else: bmp = grid_config.get_basemap_for_free_zone(resolution="f") margin = halo + blending nx = grid_config.ni if include_buffer else (grid_config.ni - 2 * grid_config.halo - 2 * grid_config.blendig) ny = grid_config.nj if include_buffer else (grid_config.nj - 2 * grid_config.halo - 2 * grid_config.blendig) ncells = nx * ny if directions_file is not None: with Dataset(directions_file) as ds: lons2d, lats2d, data = [ds.variables[k][:] for k in ["lon", "lat", nc_varname_to_show]] # Focus over the selected watersheds mask_margin = int(5 * 0.44 / grid_config.dx) # to keep the domain sizes approximately the same for all resolutions mask_margin = max(mask_margin, 1) print(mask_margin) if path_to_shape_with_focus_polygons is not None: bmp, data_mask = grid_config.get_basemap_using_shape_with_polygons_of_interest( lons2d[margin:-margin, margin:-margin], lats2d[margin:-margin, margin:-margin], shp_path=path_to_shape_with_focus_polygons, mask_margin=mask_margin, resolution="f") bmp.readshapefile(path_to_shape_with_focus_polygons[:-4], "basins", linewidth=basin_border_width, color="m") ncells = (data_mask > 0.5).sum() xxx, yyy = bmp(lons2d[margin:-margin, margin:-margin], lats2d[margin:-margin, margin:-margin]) data = data[margin:-margin, margin:-margin] if data_mask is not None: # subset the data for plotting with imshow (not required for contourf) imin, imax, jmin, jmax = get_rectangular_region_from_mask_and_margin(data_mask > 0.5, margin_points=mask_margin) data = np.ma.masked_where(data_mask < 0.5, data) data = data[imin:imax + 1, jmin:jmax + 1] print("plotting {}, range: {} ... {} ".format(nc_varname_to_show, data.min(), data.max())) lon_copy = lons2d.copy()[margin:-margin, margin:-margin] lon_copy[lon_copy > 180] -= 360 lat_copy = lats2d.copy()[margin:-margin, margin:-margin] to_plot = maskoceans(lon_copy, lat_copy, data) if clevels is not None: bn = BoundaryNorm(clevels, len(clevels) - 1) cmap = cm.get_cmap("bone_r", bn.N) im = bmp.imshow(to_plot.T, cmap=cmap, interpolation="nearest", norm=bn) else: # im = bmp.contourf(xxx, yyy, data, cmap="bone_r", norm=LogNorm()) im = bmp.imshow(to_plot.T, cmap="bone_r", interpolation="nearest", norm=LogNorm()) if draw_colorbar: # bmp.colorbar(im, format=ScalarFormatter(useMathText=True, useOffset=False)) bmp.colorbar(im) # bmp.readshapefile(default_domains.MH_BASINS_PATH[:-4], "basin", color="m", linewidth=basin_border_width) if grdc_basins_of_interest is not None: # Select which basins to show bmp.readshapefile(default_domains.GRDC_BASINS_PATH[:-4], "basin", drawbounds=False) patches = [] for info, shape in zip(bmp.basin_info, bmp.basin): if info["BASIN_ID"] in grdc_basins_of_interest: patches.append(Polygon(np.array(shape), True)) ax.add_collection( PatchCollection(patches, facecolor='none', edgecolor='r', linewidths=basin_border_width, zorder=2)) lons, lats = grid_config.get_free_zone_corners(halo=halo, blending=blending) xx, yy = bmp(lons, lats) coords = [(xx[0, 0], yy[0, 0]), (xx[0, -1], yy[0, -1]), (xx[-1, -1], yy[-1, -1]), (xx[-1, 0], yy[-1, 0])] ax.add_patch(Polygon(coords, facecolor="none")) if draw_rivers: bmp.drawrivers() bmp.drawcoastlines(linewidth=0.3, ax=ax) bmp.drawstates(linewidth=0.3, ax=ax) bmp.drawcountries(linewidth=0.3, ax=ax) bmp.drawmapboundary(fill_color="aqua") p = Path(img_folder) if not p.exists(): p.mkdir() ax.set_title(r"{} cells, $\Delta x$ = {}$^\circ$".format(ncells, grid_config.dx)) if not is_subplot: img_file = p.joinpath("{}_dx{}.png".format(imgfile_prefix, grid_config.dx)) print("Saving {}".format(img_file)) fig.savefig(str(img_file), bbox_inches="tight", transparent=False, dpi=300) plt.close(fig) return im
ax.set_xlim(d_min, d_max) ax.set_ylim(d_min, d_max) ax.set_xlabel("Intensity f(x)") ax.set_ylabel("Gradient Magnitude f'(x)") ax.set_title("2D Histogram") # Plot map for poltical borders pltMap = np.zeros((nr_bins, nr_bins, 1)).repeat(4, 2) cmapPltMap = ListedColormap([ [1, 1, 1, 0], # transparent zeros [0, 0, 0, 0.75], # political borders [1, 0, 0, 0.5], # other colors for future use [0, 0, 1, 0.5] ]) boundsPltMap = [0, 1, 2, 3, 4] normPltMap = BoundaryNorm(boundsPltMap, cmapPltMap.N) pltMapH = ax.imshow(pltMap, cmap=cmapPltMap, norm=normPltMap, vmin=boundsPltMap[1], vmax=boundsPltMap[-1], extent=[0, nr_bins, nr_bins, 0], interpolation='none') # Plot colorbar for 2d hist volHistH.set_norm(LogNorm(vmax=np.power(10, cfg.cbar_init))) fig.colorbar(volHistH, fraction=0.046, pad=0.04) # magical perfect scaling # Set up a colormap for ncut labels ncut_palette = plt.cm.gist_rainbow ncut_palette.set_under('w', 0)
#data_n256 = np.flip(data_n256, axis=0) print(data_n256.shape) #plot if OPT == 'elev': zlevels = np.arange(-6000, 6000, 10) elif OPT == 'lsm': zlevels = np.arange(0, 1, 0.01) fig = plt.figure(figsize=(18.6, 10.5)) ax = fig.add_axes((0, 0, 1, 1)) ax.set_axis_off() cmap = plt.get_cmap('bwr') norm = BoundaryNorm(zlevels, ncolors=cmap.N) plt.pcolormesh(lons_n256, lats_n256, data_n256, cmap=cmap, norm=norm, zorder=0) plt.colorbar(fraction=0.025, pad=0.01) plt.savefig("/home/kalassak/ps-capstone/scripts/pavala/topo.png", bbox_inches='tight', pad_inches=0, dpi=100) plt.close() #flatten array for output print(data_n256) data_n256 = data_n256.flatten() print(data_n256) '''
# Contour levels levels = np.linspace(cbar_min, cbar_max, 400) # Levels # Contour colormap cmap = plt.get_cmap('jet') # Colormap # RdYlGn # YlOrBr # RdBu # gist_heat # afmhot # jet # RdGy # Contour normalization norm = BoundaryNorm(levels, ncolors=cmap.N) # Normalization ################ # Contour plot # ################ if orientation == 'v': cn = ax.contourf(X1, X2, plot, cmap=cmap, levels=levels, norm=norm) cn = ax.contourf(-X1, X2, plot, cmap=cmap, levels=levels, norm=norm) if (COORD == 'CYLINDRICAL') or (COORD == 'SPHERICAL'): cn = ax.contourf(X1, -X2, plot, cmap=cmap, levels=levels, norm=norm) cn = ax.contourf(-X1, -X2, plot, cmap=cmap, levels=levels, norm=norm) if orientation == 'h': cn = ax.contourf(X2, X1, plot, cmap=cmap, levels=levels, norm=norm) if (COORD == 'CYLINDRICAL') or (COORD == 'SPHERICAL'): cn = ax.contourf(X2, -X1, plot, cmap=cmap, levels=levels, norm=norm)
def main(): start_year = 1979 end_year = 1981 HL_LABEL = "CRCM5_HL" NEMO_LABEL = "CRCM5_NEMO" dx = 0.1 dy = 0.1 file_prefix = "pm" PR_level = -1 PR_level_type = level_kinds.ARBITRARY tprecip_vname = "PR" sprecip_vname = "SN" TT_level = 1 TT_level_type = level_kinds.HYBRID sim_label_to_path = OrderedDict([ (HL_LABEL, "/RESCUE/skynet3_rech1/huziy/CNRCWP/C5/2016/2-year-runs/coupled-GL+stfl_oneway/Samples" ), (NEMO_LABEL, "/HOME/huziy/skynet3_rech1/CNRCWP/C5/2016/2-year-runs/coupled-GL+stfl/Samples" ) ]) # get a coord file ... (use pm* files, since they contain NEM1 variable) # Should be NEMO_LABEL, since the hostetler case does not calculate NEM? vars coord_file = "" found_coord_file = False for mdir in os.listdir(sim_label_to_path[NEMO_LABEL]): mdir_path = os.path.join(sim_label_to_path[NEMO_LABEL], mdir) if not os.path.isdir(mdir_path): continue for fn in os.listdir(mdir_path): if fn[:2] not in [ "pm", ]: continue if fn[-9:-1] == "0" * 8: continue coord_file = os.path.join(mdir_path, fn) found_coord_file = True if found_coord_file: break bmp, lons, lats = nemo_hl_util.get_basemap_obj_and_coords_from_rpn_file( path=coord_file) xx, yy = bmp(lons, lats) r = RPN(coord_file) lats_rot = r.get_first_record_for_name("^^") lons_rot = r.get_first_record_for_name(">>") lake_mask = np.greater( commons.get_nemo_lake_mask_from_rpn(coord_file, vname="NEM1"), 0) # Get the 100km region around the lakes lake_effect_regions = get_mask_of_points_near_lakes(lake_mask, npoints_radius=10) local_amplification_limit = 4 * 1e-2 / (24.0 * 3600.0) # the radius is 500 km, i.e. 50 gridpoints ij_to_non_local_mask = get_map_ij_to_nonlocal_mask(lake_effect_regions, lake_mask, npoints_radius=50) # Snowfall amount criteria (>= 10 cm) lower_snow_fall_limit = 10 * 1e-2 / (24.0 * 3600.0) # convert to M/s # wind blows from lake: time limit wind_blows_from_lake_time_limit_hours = 6.0 months_of_interest = [10, 11, 12, 1, 2, 3, 4, 5] sim_label_to_duration_mean = {} sim_label_to_lake_effect_sprecip_mean = {} sim_label_to_year_to_lake_effect_snow_fall_duration = OrderedDict([ (sim_label, OrderedDict()) for sim_label in sim_label_to_path ]) for sim_label, samples_dir_path in sim_label_to_path.items(): # calculate the composites for the (Oct - March) period lake_effect_snowfall_mean_duration = None # the duration is in time steps lake_effect_mean_snowrate_m_per_s = None snowfall_current_event = None duration_current_event = None # the duration is in time steps n_events = None sn_previous = None time_wind_blows_from_lake = None samples_dir = Path(samples_dir_path) snowfall_file = samples_dir.parent / "{}_snow_fall_{}-{}.nc".format( sim_label, start_year, end_year) wind_components_file = samples_dir.parent / "rotated_wind_{}.nc".format( sim_label) ds_wind = Dataset(str(wind_components_file)) print("Working on {} ...".format(sim_label)) lkice_manager = RPNLakeIceManager(samples_dir=samples_dir) with Dataset(str(snowfall_file)) as ds: time_var = ds.variables["time"] nt = time_var.shape[0] snowfall_var_m_per_s = ds.variables["SN"] u_var = ds_wind.variables["UU"] v_var = ds_wind.variables["VV"] time_var_wind = ds_wind.variables["time"] assert time_var_wind.shape == time_var.shape assert time_var_wind[0] == time_var[0] assert time_var_wind[-1] == time_var_wind[-1] assert (u_var.shape == snowfall_var_m_per_s.shape) and ( v_var.shape == snowfall_var_m_per_s.shape) times = num2date(time_var[:], time_var.units) dt_seconds = (times[1] - times[0]).total_seconds() year_to_lake_effect_snow_fall_duration = sim_label_to_year_to_lake_effect_snow_fall_duration[ sim_label] for ti, t in enumerate(times): if t.month not in months_of_interest: continue if t.year > end_year or t.year < start_year: continue sn_current = snowfall_var_m_per_s[ti, :, :] if t.year not in year_to_lake_effect_snow_fall_duration: year_to_lake_effect_snow_fall_duration[ t.year] = np.zeros_like(sn_current) # initialize aggragtion fields if lake_effect_snowfall_mean_duration is None: lake_effect_snowfall_mean_duration = np.zeros_like( sn_current) lake_effect_mean_snowrate_m_per_s = np.zeros_like( sn_current) n_events = np.zeros_like(sn_current) snowfall_current_event = np.zeros_like(sn_current) duration_current_event = np.zeros_like(sn_current) sn_previous = np.zeros_like(sn_current) time_wind_blows_from_lake = np.zeros_like(sn_current) where_lake_effect_snow = ( sn_current > lower_snow_fall_limit) & lake_effect_regions & (~lake_mask) # add a condition on the local amplification i_arr, j_arr = np.where(where_lake_effect_snow) for i, j in zip(i_arr, j_arr): the_mask = ij_to_non_local_mask[(i, j)] where_lake_effect_snow[i, j] = sn_current[the_mask].mean( ) < sn_current[i, j] - local_amplification_limit # add a condition on the wind fetch from lakes and ice fraction. wind_blows_from_lake = get_wind_blows_from_lake_mask( lake_mask, lake_effect_regions, u_var[ti, :, :], v_var[ti, :, :], dx=dx, dy=dy, lake_ice_frac=lkice_manager.get_lake_fraction_for_date( the_date=t), lats_rot=lats_rot) time_wind_blows_from_lake[ wind_blows_from_lake] += dt_seconds / 3600.0 where_lake_effect_snow = where_lake_effect_snow & ( time_wind_blows_from_lake >= wind_blows_from_lake_time_limit_hours) time_wind_blows_from_lake[~wind_blows_from_lake] = 0 # update accumulators for current lake effect snowfall events snowfall_current_event[where_lake_effect_snow] += sn_current[ where_lake_effect_snow] duration_current_event[where_lake_effect_snow] += 1.0 where_lake_effect_snow_finished = (~where_lake_effect_snow) & ( sn_previous > lower_snow_fall_limit) # recalculate mean lake effect snowfall duration and rate lake_effect_snowfall_mean_duration[ where_lake_effect_snow_finished] = ( lake_effect_snowfall_mean_duration[ where_lake_effect_snow_finished] * n_events[where_lake_effect_snow_finished] + duration_current_event[where_lake_effect_snow_finished] ) / (n_events[where_lake_effect_snow_finished] + 1) lake_effect_mean_snowrate_m_per_s[ where_lake_effect_snow_finished] = ( lake_effect_mean_snowrate_m_per_s[ where_lake_effect_snow_finished] * n_events[where_lake_effect_snow_finished] + snowfall_current_event[where_lake_effect_snow_finished] ) / (n_events[where_lake_effect_snow_finished] + 1) year_to_lake_effect_snow_fall_duration[t.year][ where_lake_effect_snow_finished] += duration_current_event[ where_lake_effect_snow_finished] * dt_seconds # reset the current accumulators snowfall_current_event[where_lake_effect_snow_finished] = 0 duration_current_event[where_lake_effect_snow_finished] = 0 n_events[where_lake_effect_snow_finished] += 1 sn_previous = sn_current if ti % 1000 == 0: print("Done {} of {}".format(ti + 1, nt)) # normalization lake_effect_snowfall_mean_duration *= dt_seconds / ( 24 * 60 * 60.0) # convert to days lake_effect_mean_snowrate_m_per_s = np.ma.masked_where( ~lake_effect_regions, lake_effect_mean_snowrate_m_per_s) lake_effect_snowfall_mean_duration = np.ma.masked_where( ~lake_effect_regions, lake_effect_snowfall_mean_duration) for y, yearly_durations in sim_label_to_year_to_lake_effect_snow_fall_duration[ sim_label].items(): sim_label_to_year_to_lake_effect_snow_fall_duration[sim_label][ y] = np.ma.masked_where(~lake_effect_regions, yearly_durations) / (24 * 3600.0) sim_label_to_duration_mean[ sim_label] = lake_effect_snowfall_mean_duration sim_label_to_lake_effect_sprecip_mean[ sim_label] = lake_effect_mean_snowrate_m_per_s * 100 * 24 * 3600.0 # close the file with rotated wind components ds_wind.close() plot_utils.apply_plot_params(font_size=6, width_cm=18, height_cm=10) fig = plt.figure() gs = GridSpec(3, 3) duration_clevs = 20 # np.arange(0, 1.1, 0.1) snowrate_clevs = 20 # np.arange(0, 36, 4) duration_clevs_diff = 20 # np.arange(-1, 1.1, 0.1) snowrate_clevs_diff = 20 # np.arange(-10, 12, 2) vmax_duration = None vmax_snowrate = None vmax_days_per_year = None for row, sim_label in enumerate(sim_label_to_path): if vmax_duration is None: vmax_duration = sim_label_to_duration_mean[sim_label].max() vmax_snowrate = sim_label_to_lake_effect_sprecip_mean[ sim_label].max() vmax_days_per_year = sim_label_to_year_to_lake_effect_snow_fall_duration[ sim_label][1980].max() else: vmax_duration = max(vmax_duration, sim_label_to_duration_mean[sim_label].max()) vmax_snowrate = max( vmax_snowrate, sim_label_to_lake_effect_sprecip_mean[sim_label].max()) vmax_days_per_year = max( vmax_days_per_year, sim_label_to_year_to_lake_effect_snow_fall_duration[sim_label] [1980].max()) for col, sim_label in enumerate(sim_label_to_path): # plot the duration of lake-effect snow events ax = fig.add_subplot(gs[0, col]) cs = bmp.pcolormesh(xx, yy, sim_label_to_duration_mean[sim_label], ax=ax, vmin=0, vmax=vmax_duration, cmap="rainbow_r") bmp.drawcoastlines(linewidth=0.3, ax=ax) plt.colorbar(cs, ax=ax) ax.set_title("Duration (days)") ax.set_xlabel("{}".format(sim_label)) # plot the mean intensity of the lake-effect snow events ax = fig.add_subplot(gs[1, col]) cs = bmp.pcolormesh(xx, yy, sim_label_to_lake_effect_sprecip_mean[sim_label], ax=ax, vmax=vmax_snowrate, vmin=lower_snow_fall_limit, cmap="rainbow_r") bmp.drawcoastlines(linewidth=0.3, ax=ax) plt.colorbar(cs, ax=ax) ax.set_title("Snowfall rate, (cm/day)") ax.set_xlabel("{}".format(sim_label)) # plot the mean duration of the lake effect snowfall events per year ax = fig.add_subplot(gs[2, col]) to_plot = sim_label_to_year_to_lake_effect_snow_fall_duration[ sim_label][1980] clevs = [ 0, 0.1, ] + list(np.arange(0.4, 3.2, 0.4)) bn = BoundaryNorm(clevs, len(clevs)) cmap = cm.get_cmap("spectral_r", len(clevs)) cs = bmp.pcolormesh(xx, yy, to_plot, ax=ax, norm=bn, cmap=cmap) bmp.drawcoastlines(linewidth=0.3, ax=ax) plt.colorbar(cs, ax=ax, extend="max") ax.set_title("# Days per year") ax.set_xlabel("{}".format(sim_label)) # plot the difference # plot the duration of lake-effect snow events col = 2 cmap = cm.get_cmap("seismic", 40) vmin = -np.max(sim_label_to_duration_mean[NEMO_LABEL] - sim_label_to_duration_mean[HL_LABEL]) ax = fig.add_subplot(gs[0, col]) cs = bmp.pcolormesh(xx, yy, sim_label_to_duration_mean[NEMO_LABEL] - sim_label_to_duration_mean[HL_LABEL], vmin=vmin, ax=ax, cmap=cmap) plt.colorbar(cs, ax=ax) bmp.drawcoastlines(linewidth=0.3, ax=ax) ax.set_title("Duration (days)") ax.set_xlabel("{} - {}".format(NEMO_LABEL, HL_LABEL)) # plot the mean intensity of the lake-effect snow events ax = fig.add_subplot(gs[1, col]) vmin = -np.max(sim_label_to_lake_effect_sprecip_mean[NEMO_LABEL] - sim_label_to_lake_effect_sprecip_mean[HL_LABEL]) cs = bmp.pcolormesh(xx, yy, sim_label_to_lake_effect_sprecip_mean[NEMO_LABEL] - sim_label_to_lake_effect_sprecip_mean[HL_LABEL], ax=ax, vmin=vmin, cmap=cmap) # convert to cm/day bmp.drawcoastlines(linewidth=0.3, ax=ax) plt.colorbar(cs, ax=ax) ax.set_title("Snowfall rate, (cm/day)") ax.set_xlabel("{} - {}".format(NEMO_LABEL, HL_LABEL)) # plot the mean duration of the lake effect snowfall events per year ax = fig.add_subplot(gs[2, col]) to_plot = ( sim_label_to_year_to_lake_effect_snow_fall_duration[NEMO_LABEL][1980] - sim_label_to_year_to_lake_effect_snow_fall_duration[HL_LABEL][1980]) cs = bmp.pcolormesh(xx, yy, to_plot, ax=ax, vmin=-to_plot.max(), cmap="seismic") bmp.drawcoastlines(linewidth=0.3, ax=ax) plt.colorbar(cs, ax=ax) ax.set_title("# Days per year") ax.set_xlabel("{} - {}".format(NEMO_LABEL, HL_LABEL)) fig.tight_layout() fig.savefig(os.path.join( img_folder, "lake_effect_snow_10cm_limit_and_loc_ampl_{}-{}.png".format( start_year, end_year)), dpi=commons.dpi, transparent=True, bbox_inches="tight")
lonlim = [-90, -30] #longitude limits data = ['ERA5', 'UKMO', 'NCEP', 'ECMWF'] #dataset titles #Zeng's gamma plot cmap = plt.get_cmap('RdBu') cmap.set_bad(color='0.75', alpha=1.) cmin = -0.2 cmax = 0.2 cspc = 0.01 cstp = 0.1 clevs = np.arange(cmin, cmax + cspc, cspc) label = 'Gamma' title = 'PR-ET' units = '' clabel = label + ' ' + title + ' ' + units norm = BoundaryNorm(boundaries=clevs, ncolors=256) fig = plt.figure(figsize=(12, 9)) ax = plt.subplot(4, 5, 3) mymap = Basemap(projection='cyl', resolution='l', llcrnrlat=latlim[0], urcrnrlat=latlim[1], llcrnrlon=lonlim[0], urcrnrlon=lonlim[1]) mymap.drawcoastlines(linewidth=lw) mymap.drawcountries(linewidth=lw) mymap.drawparallels(np.arange(-90, 90, gl), labels=[1, 0, 0, 1], labelstyle='+/-') mymap.drawmeridians(np.arange(0, 360, gl), labels=[0, 0, 0, 0],
def main(): dmManager = Crcm5ModelDataManager(samples_folder_path=rpn_folder, file_name_prefix="dm", all_files_in_samples_folder=True) pmManager = Crcm5ModelDataManager(samples_folder_path=rpn_folder, file_name_prefix="pm", all_files_in_samples_folder=True) #export monthly means to netcdf files if necessary if export_to_nc: for varname, prefix in zip(field_names, file_name_prefixes): manager = None if prefix == "dm": manager = dmManager elif prefix == "pm": manager = pmManager level = -1 level_kind = -1 if varname == "TT": level = 1 level_kind = level_kinds.HYBRID if varname in ["TRAF", "TDRA"]: level = 1 level_kind = level_kinds.ARBITRARY if varname == "STFA": continue export_monthly_means_to_ncdb(manager, varname, level=level, level_kind=level_kind, rewrite=True) #plot results assert isinstance(pmManager, Crcm5ModelDataManager) lons, lats = pmManager.lons2D, pmManager.lats2D basemap = Crcm5ModelDataManager.get_rotpole_basemap_using_lons_lats( lons2d=lons, lats2d=lats) x, y = basemap(lons, lats) nc_data_folder = os.path.join(nc_db_folder, sim_name) import matplotlib.pyplot as plt all_axes = [] ax_to_levels = {} imgs = [] gs = gridspec.GridSpec(2, 3, height_ratios=[1, 1], width_ratios=[1, 1, 1]) fig = plt.figure() #fig.suptitle("({0} - {1})".format(start_year, end_year)) #plot Temp varname = "TT" levels = [-30, -25, -10, -5, -2, 0, 2, 5, 10, 15, 20, 25] cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ds = Dataset(os.path.join(nc_data_folder, "{0}.nc4".format(varname))) years = ds.variables["year"][:] sel = np.where((start_year <= years) & (years <= end_year))[0] tt = ds.variables[varname][sel, :, :, :].mean(axis=0).mean(axis=0) ds.close() ax = fig.add_subplot(gs[0, 0]) ax.set_title("Temperature (${\\rm ^\circ C}$)") img = basemap.contourf(x, y, tt, levels=levels, cmap=cmap, norm=bn) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot precip varname = "PR" levels = np.arange(0, 6.5, 0.5) cmap = cm.get_cmap("jet_r", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ds = Dataset(os.path.join(nc_data_folder, "{0}.nc4".format(varname))) years = ds.variables["year"][:] sel = np.where((start_year <= years) & (years <= end_year))[0] pr = ds.variables[varname][sel, :, :, :].mean(axis=0).mean(axis=0) convert_factor = 1000.0 * 24 * 60 * 60 #m/s to mm/day pr *= convert_factor ds.close() ax = fig.add_subplot(gs[0, 1]) ax.set_title("Precip (mm/day)") img = basemap.contourf(x, y, pr, levels=levels, cmap=cmap, norm=bn) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot AH varname = "AH" ds = Dataset(os.path.join(nc_data_folder, "{0}.nc4".format(varname))) years = ds.variables["year"][:] sel = np.where((start_year <= years) & (years <= end_year))[0] ah = ds.variables[varname][sel, :, :, :].mean(axis=0).mean(axis=0) ds.close() levels = np.arange(-60, 160, 20) # np.linspace(au.min(), au.max(), 10) cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ax = fig.add_subplot(gs[1, 0]) ax.set_title("Sensible heat flux (${\\rm W/m^2}$)") img = basemap.contourf(x, y, ah, cmap=cmap, norm=bn, levels=levels) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot AV varname = "AV" ds = Dataset(os.path.join(nc_data_folder, "{0}.nc4".format(varname))) years = ds.variables["year"][:] sel = np.where((start_year <= years) & (years <= end_year))[0] av = ds.variables[varname][sel, :, :, :].mean(axis=0).mean(axis=0) ds.close() coef = 3600 * 3 levels = np.arange(-40, 220, 20) cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ax = fig.add_subplot(gs[1, 1]) ax.set_title("Latent heat flux (${\\rm W/m^2}$)") img = basemap.contourf(x, y, av * coef, levels=levels, cmap=cmap, norm=bn) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels #plot stfl varname = "STFL" ds = Dataset(os.path.join(nc_data_folder, "{0}.nc4".format(varname))) years = ds.variables["year"][:] sel = np.where((start_year <= years) & (years <= end_year))[0] stfl = ds.variables[varname][sel, :, :, :].mean(axis=0).mean(axis=0) ds.close() levels = [ 0, 50, 100, 200, 300, 500, 750, 1000, 1500, 2000, 5000, 10000, 15000 ] stfl = np.ma.masked_where(stfl < 0.01, stfl) cmap = cm.get_cmap("jet", len(levels) - 1) bn = BoundaryNorm(levels, cmap.N) ax = fig.add_subplot(gs[0, 2]) ax.set_title("Streamflow (${\\rm m^3/s}$)") img = basemap.contourf(x, y, stfl, levels=levels, cmap=cmap, norm=bn) all_axes.append(ax) imgs.append(img) ax_to_levels[ax] = levels sf = ScalarFormatter(useMathText=True) sf.set_powerlimits([-3, 4]) #draw coast lines for the_ax, the_img in zip(all_axes, imgs): basemap.drawcoastlines(ax=the_ax) divider = make_axes_locatable(the_ax) cax = divider.append_axes("right", "5%", pad="3%") cb = plt.colorbar(the_img, cax=cax, ticks=ax_to_levels[the_ax]) assert isinstance(cax, Axes) title = cax.get_title() fig.tight_layout() fig.savefig("{0}-mean-annual-fields.pdf".format(sim_name))
olons = o.lon panel_titles = ('WRF', 'Erai-Interim', 'Diff') ylabel = ('00h UTC', '06h UTC', '12h UTC', '18h UTC') # Plot figure with subplots of different sizes fig = plt.figure(1) # set up subplot grid gridspec.GridSpec(6, 6) vmin = 273 vmax = 313 tot_levels = 11 levels = list(np.linspace(vmin, vmax, tot_levels)) custom_cmap = plt.get_cmap('afmhot_r') norm = BoundaryNorm(levels, ncolors=custom_cmap.N, clip=True) # large subplot - 6hourly obs (Era-Interim) axOBS = plt.subplot2grid((6, 6), (1, 2), colspan=2, rowspan=3) m = Basemap(projection='cyl', llcrnrlat=-60., urcrnrlat=20., llcrnrlon=-90., urcrnrlon=-20., lon_0=0, resolution='i', ax=axOBS) m.drawcountries(linewidth=0.25) m.drawcoastlines(linewidth=0.50) h = m.pcolormesh(lons, lats,
#print(Mesh_Nex) else: k = idx idx_x = int(k / G_size) ind_y = k % G_size Mesh_Nex[idx_x][idx_y] += df_points[ (df_points['vx'] == kd_points[i][0]) & (df_points['vy'] == kd_points[i][1])]['Nex'] #4, use pcolormesh to plot. #4.0 color and norm settings #cmap = plt.get_cmap('RdBu') cmap = plt.get_cmap('seismic') levels = MaxNLocator(nbins=1000).tick_values(df_points.Nex.min(), df_points.Nex.max()) normal = BoundaryNorm(levels, ncolors=cmap.N, clip=True) #4.1 plot fig, ax0 = plt.subplots(figsize=(10, 8)) #ax.plot(df_points.vx, df_points.vy, "kx", alpha=0.2) #mapper = ax.scatter(df_grid.vx, df_grid.vy, c=df_grid.Nex, # cmap="viridis", # linewidths=0, # s=100, marker="o") #, norm=normal) #plt.colorbar(mapper, ax=ax) #scat = ax.scatter(x, y, c=z, s=200) #fig.colorbar(scat) #ax.margins(0.05) im = plt.pcolormesh(grid2d_x, grid2d_y, Mesh_Nex, cmap=cmap,
class LULC(enum.Enum): BACKGROUND = (0, 'Background', 'black') NO_DATA = (1, 'No Data', 'white') NO_DAMAGE = (2, 'No damage', 'xkcd:lime') MINOR_DAMAGE = (3, 'Minor Damage', 'yellow') MAJOR_DAMAGE = (4, 'Major Damage', 'orange') DESTROYED = (5, 'Destroyed', 'red') def __init__(self, val1, val2, val3): self.id = val1 self.class_name = val2 self.color = val3 lulc_cmap = ListedColormap([entry.color for entry in LULC]) lulc_norm = BoundaryNorm(np.arange(-0.5, 6, 1), lulc_cmap.N) def gpu_stats(): max_memory_allocated = torch.cuda.max_memory_allocated( ) / 1e6 # bytes to MB max_memory_cached = torch.cuda.max_memory_cached() / 1e6 return int(max_memory_allocated), int(max_memory_cached) def setup(args): cfg = new_config() cfg.merge_from_file(f'configs/urban_extraction/{args.config_file}.yaml') cfg.merge_from_list(args.opts) cfg.NAME = args.config_file
def plot_treatment_assignment(dataset, dimensionality_reducer=UMAP( n_neighbors=5, min_dist=0.1, metric="correlation"), alpha=0.25, marker="o", markersize=20, histogram=True, colors={ "treated": "yellow", "control": "purple" }, axes=None): assert len( colors.keys()) == 2, "Only binary treatment assignment is supported!" if histogram and axes is not None: assert len( axes ) == 2, "Need to pass one axis for the scatter plot and one for the histogram." embedding = dimensionality_reducer.fit_transform(dataset.covariates) colorbar_axis = None if axes is None: fig, (ax, colorbar_axis, histogram_axis) = plt.subplots( ncols=3, gridspec_kw={"width_ratios": [1, 0.03, 1]}) plt.tight_layout() else: ax, histogram_axis = axes treated = embedding[dataset.treatment_assignment == 1] control = embedding[dataset.treatment_assignment == 0] cmap = plt.cm.jet cmap = cmap.from_list("Treated vs control cmap", [colors["control"], colors["treated"]], len(colors)) ax.scatter( np.asarray(treated[:, 0].tolist() + control[:, 0].tolist()), np.asarray(treated[:, 1].tolist() + control[:, 1].tolist()), cmap=cmap, c=dataset.treatment_assignment, alpha=alpha, marker=marker, s=markersize, ) ax.set_title('Units: treated vs control') plt.setp(ax, xticks=[], yticks=[]) if histogram: histogram_axis.hist(["Treated"] * (dataset.treatment_assignment == 1.).sum() + ["Control"] * (dataset.treatment_assignment == 0.).sum()) if colorbar_axis is not None: cb = mpl.colorbar.ColorbarBase(colorbar_axis, cmap=cmap, norm=BoundaryNorm((0, 1, 2), ncolors=2), ticks=(0.5, 1.5), spacing='proportional', orientation="vertical") cb.set_ticklabels(("Control", "Treated")) colorbar_axis.tick_params(axis=u'both', which=u'both', length=0) return (ax, colorbar_axis, histogram_axis) return ax, histogram_axis
#global variables dt = 1 dy = 1 max_t = 100 max_y = 1024 set_t = 3000 fig = plt.figure() data = np.zeros((max_t, max_y)) #define and initialize data to 0 infile = open("dummy.txt", 'r') #input data file #color setting for pcolormesh cmap = plt.get_cmap('jet') norm = BoundaryNorm([i for i in range(-80, 1)], ncolors=cmap.N, clip=True) extent = ((-max_t, 0, 0, max_y)) im = plt.imshow(data.T, cmap=cmap, norm=norm, animated=True, extent=extent, aspect='auto') fig.colorbar(im) def init(): return def animate(time):
def _plot_warn( self, run_datetime, thresholds, decision_level, decision_dict, polygon_file, polygon_file_crs, title, proj=ccrs.PlateCarree(), figsize=(9, 13), adapt_fontsize=True, ): """plotting the warning level of each warning region based on thresholds""" # select hazard with run_datetime if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] kwargs = dict() kwargs["cmap"] = CMAP_WARNPROB kwargs["s"] = 5 kwargs["marker"] = "," kwargs["norm"] = BoundaryNorm(np.linspace(0, 1, 11), CMAP_WARNPROB.N, clip=True) # Generate each subplot fig, axis, _fontsize = u_plot.make_map(1, proj=proj, figsize=figsize, adapt_fontsize=adapt_fontsize) if isinstance(axis, np.ndarray): axis = axis[0] tit = title fig.set_size_inches(9, 8) # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs(polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) # checking the decision dict and define the corresponding functions if not (isinstance(decision_dict["probability_aggregation"], float) & isinstance(decision_dict["area_aggregation"], float)): ValueError(" If decision_level is 'exposure_point'," + "parameters probability_aggregation and " + "area_aggregation of " + "Forecast.plot_warn_map() must both be " + "floats between [0..1]. Which each " + "specify quantiles.") decision_dict_functions = decision_dict.copy() for aggregation in decision_dict: if isinstance(decision_dict[aggregation], float): decision_dict_functions[aggregation] = np.percentile elif decision_dict[aggregation] == "sum": decision_dict_functions[aggregation] = np.sum elif decision_dict[aggregation] == "mean": decision_dict_functions[aggregation] = np.mean else: raise ValueError("Parameter area_aggregation of " + "Forecast.plot_warn_map() must eiter be " + "a float between [0..1], which " + "specifys a quantile. or 'sum' or 'mean'.") for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) in_geom = u_coord.coord_on_land( lat=self._impact[haz_ind].coord_exp[:, 0], lon=self._impact[haz_ind].coord_exp[:, 1], land_geom=geom2, ) if not in_geom.any(): continue # decide warning level warn_level = 0 for ind_i, warn_thres_i in enumerate(thresholds): if decision_level == "exposure_point": # decision at each grid_point probabilities = np.squeeze( np.asarray((self._impact[haz_ind].imp_mat >= warn_thres_i).sum(axis=0) / self._impact[haz_ind].event_id.size)) # quantiles over probability area = (probabilities[in_geom] >= decision_dict["probability_aggregation"]).sum() # quantiles over area if area >= (in_geom.sum() * decision_dict["area_aggregation"]): warn_level = ind_i + 1 elif decision_level == "polygon": # aggregation over area if isinstance(decision_dict["area_aggregation"], float): value_per_member = decision_dict_functions[ "area_aggregation"]( self._impact[haz_ind].imp_mat[:, in_geom].todense( ), decision_dict["area_aggregation"], axis=1, ) else: value_per_member = decision_dict_functions[ "area_aggregation"](self._impact[haz_ind]. imp_mat[:, in_geom].todense(), axis=1) # aggregation over members/probability if isinstance(decision_dict["probability_aggregation"], float): value_per_region = decision_dict_functions[ "probability_aggregation"]( value_per_member, decision_dict["probability_aggregation"]) else: value_per_region = decision_dict_functions[ "probability_aggregation"](value_per_member) # warn level decision if value_per_region >= warn_thres_i: warn_level = ind_i + 1 else: raise ValueError( "Parameter decision_level of " + "Forecast.plot_warn_map() must eiter be " + "'exposure_point' or 'polygon'.") # plot warn_region with specific color (dependent on warning level) axis.add_geometries( [geom2], crs=ccrs.PlateCarree(), facecolor=COLORS_WARN[warn_level, :], edgecolor="gray", ) # Create legend in this axis hazard_levels = [ "1: Minimal or no hazard", "2: Moderate hazard", "3: Significant hazard", "4: Severe hazard", "5: Very severe hazard", ] legend_elements = [ Patch(facecolor=COLORS_WARN[n, :], edgecolor="gray", label=hazard_level) for n, hazard_level in enumerate(hazard_levels) ] axis.legend( handles=legend_elements, loc="upper center", framealpha=0.5, bbox_to_anchor=(0.5, -0.02), ncol=3, ) title_position = { "model_text": [0.02, 0.91], "explain_text": [0.02, 0.87], "event_day": [0.98, 0.91], "run_start": [0.98, 0.87], } left_right = { "model_text": "left", "explain_text": "left", "event_day": "right", "run_start": "right", } color = { "model_text": "k", "explain_text": "k", "event_day": "r", "run_start": "k", } for t_i in tit: plt.figtext( title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize="xx-large", color=color[t_i], ha=left_right[t_i], ) extent = u_plot._get_borders(self._impact[haz_ind].coord_exp) axis.set_extent((extent), ccrs.PlateCarree()) fig.tight_layout() return fig, axis