def plot_bolivia_elevation(PROJ, ax2, bar_legend, grid_style, lala, levels, lola_extent, lolo, lon_large_ticks, ncmap, topo_ds, white_grid_color): ax = fa.get_ax_bolivia(chc_lp_legend=False, ax=ax2, plot_cities=False, lola_extent=lola_extent, plot_ocean=True, lola_ticks=[lolo, lala], draw_labels=False, grid_style=grid_style, grid_color=white_grid_color, grid_alpha=1, map_res='110m', xlab_bot=False, ylab_left=False) # ax.set_yticks([-20,0],crs=ccrs.PlateCarree()) ax.set_ylabel(None) ax.set_xticks(lon_large_ticks, crs=PROJ) ax.set_xlabel(None) slice_ = {'lat': slice(None, None, 10), 'lon': slice(None, None, 10)} band_ = topo_ds['Band1'][slice_] / 1000 band_ = band_.where(band_ > 0) band_.name = bar_legend band_.plot( cmap=ncmap, ax=ax, levels=levels, subplot_kws={'transform': PROJ}, # center=2000, norm=Normalize(0, 5, clip=False), add_colorbar=False, rasterized=True) ax.set_xlabel(None) ax.set_ylabel(None)
def plot_cluster_map( self, i, log_plot_dic=None, map_dic=None, par_to_plot=co.COL, ): if map_dic is None: map_dic = {} if log_plot_dic is None: log_plot_dic = {} clus = self.cluster_flags[i] boo = self.merged_ds[co.ClusFlag] == clus ax = fa.get_ax_bolivia(**map_dic) # fig,ax = plt.subplots() warnings.simplefilter('ignore') ar = self.merged_ds.where(boo)[par_to_plot] com = fa.get_dims_complement(ar, [co.R_CENTER, co.TH_CENTER]) ar = ar.sum(dim=com) if par_to_plot is co.CPer: ar = ar / self.merged_ds[par_to_plot].sum() * 100 cmap = fa.get_custom_cmap(self.colors[i]) def_dic = dict(ax=ax, name=par_to_plot, perM=.95, quantile=True, colorbar=False, patch_args={'cmap': cmap}) com_dic = {**def_dic, **log_plot_dic} fa.logpolar_plot(ar, **com_dic)
def plot_bolivia(ax, da_srl, name, r, t0, t1, tlen): da_th_r = da_srl.sum([co.ZM, co.RL]) ax: plt.Axes = fa.get_ax_bolivia(ax=ax) patch = fa.logpolar_plot(da_th_r.to_dataset(), ax=ax, name=co.CONC, return_patch=True, colorbar=False) ax.set_title( f'{name}:{r[name]} | {r[t0]} - {r[t1]} | {tlen}:{int(r[tlen])}') return patch
def plot_general(ds1): cl = co.CPer c1 = ds1[cl].sum([co.RL, co.ZM]) c2 = ds1[cl].sum([co.ZM, co.RL, co.TH_CENTER]) ar = c1 / c2 # ar = c1 ar = ar.isel(**{co.R_CENTER: slice(0, -3)}) ax = fa.get_ax_bolivia(fig_args={'figsize': (5, 5)}) fa.logpolar_plot(ar, name=co.CPer, ax=ax, perM=.95, perm=.01) ax.set_xlim(-75, -60) ax.set_ylim(-25, -7) return ax
def plot_clust_in_bolivia(_n, dscc): ax = fa.get_ax_bolivia() _f = 2 for _f in range(_n): _ds = dscc.loc[{co.CLUS_LENGTH_DIM: _n}] _ds = _ds.drop(co.KMEAN_OBJ) _ds = _ds.where(_ds[co.FLAG] == _f) _ds = _ds.sum([co.RL, co.ZM]) _ds = _ds[[co.CONC]] _cm = fa.get_custom_cmap(ucp.cc[_f][:3]) fa.logpolar_plot(_ds, ax=ax, patch_args={'cmap': _cm}, colorbar=False)
def plot_clust_bolivia_individual(_n, dscc): for _f in range(_n): ax = fa.get_ax_bolivia() ax.set_title(str(_f)) _ds = dscc.loc[{co.CLUS_LENGTH_DIM: _n}] _ds = _ds.drop(co.KMEAN_OBJ) _ds = _ds.where(_ds[co.FLAG] == _f) _ds = _ds.sum([co.RL, co.ZM]) _ds = _ds[[co.CONC]] _cm = fa.get_custom_cmap([*ucp.cc, *ucp.cc, *ucp.cc][_f][:3]) fa.logpolar_plot(_ds, ax=ax, patch_args={'cmap': _cm}, colorbar=False)
def plot_bolivia_domains(PROJ, ax1, dark_grid_color, grid_style, lala, lat_large_ticks, lola_extent, lolo, lon_large_ticks): ax = fa.get_ax_bolivia(ax=ax1, chc_lp_legend=False, lola_extent=lola_extent, plot_cities=False, lola_ticks=[lolo, lala], draw_labels=False, grid_style=grid_style, grid_color=dark_grid_color, grid_alpha=1, map_res='110m', xlab_bot=False, ylab_left=False) ax.set_yticks(lat_large_ticks, crs=PROJ) ax.set_ylabel(None) ax.set_xticks(lon_large_ticks, crs=PROJ) ax.set_xlabel(None) add_doms_bolivia(PROJ, ax1)
def get_topoline(zline=3900): import scipy.ndimage topo_ds = xr.open_dataset(pjoin(co.tmp_data_path, 'etopo1_bedrock.nc')) ax = fa.get_ax_bolivia() band_: xr.DataArray = topo_ds['Band1'] band_.values = scipy.ndimage.gaussian_filter(band_.values, sigma=5, truncate=10) res = band_.plot.contour(levels=[0, zline], ax=ax) ax.figure.clear() segs = res.allsegs[1] data_ser = pd.DataFrame(segs, columns=['data']) data_ser['l'] = data_ser['data'].apply(lambda l: len(l)) data_ser = data_ser.sort_values('l', ascending=False).iloc[0]['data'] seg = data_ser.T return seg
axfig.set_ylabel('sdfsdf') axfig.set_xticks([]) axfig.set_yticks([]) ax.figure # %% lab = '(# particles [%] * (residence time))' fig = self.plot_clusters_inlfuence(ylab='') fig.text(0.5, 0.1, 'release time (UTC)', ha='center', va='center') fig.text(0.1, 0.5, lab, ha='center', va='center', rotation='vertical') # %% # %% i = 0 ax = fa.get_ax_bolivia() for i in range(len_clus): clus = self.cluster_flags[i] boo = self.merged_ds[co.ClusFlag] == clus # fig,ax = plt.subplots() import warnings warnings.simplefilter('ignore') ar = self.merged_ds.where(boo)[co.CPer].mean(dim=[co.RL]) fa.logpolar_plot(ar, ax, name=co.CPer, perM=.15, quantile=False, colorbar=False, patch_args={'cmap': fa.get_custom_cmap(FLP.COLORS[i])})
dsF= self.filter_hours_with_few_mea() # %% dsSM = ds1 = FLP.smooth_merged_ds( dsF ) # %% cl = co.CPer c1 =ds1[cl].sum([co.RL,co.ZM]) c2 = ds1[cl].sum([co.ZM,co.RL,co.TH_CENTER]) ar = c1/c2 # ar = c1 ar = ar.isel(**{co.R_CENTER:slice(0,-3)}) ax = fa.get_ax_bolivia(fig_args={'figsize':(5,5)}) fa.logpolar_plot(ar,name=co.CPer,ax=ax,perM=.95,perm=.01) ax.set_xlim(-75,-60) ax.set_ylim(-25,-7) # ax = fa.get_ax_lapaz() # fa.logpolar_plot(ar,name=co.CPer,ax=ax,perM=.95) # %% ax.figure.savefig('/tmp/map.pdf') # %% # %% ds1.sum([co.ZM,co.RL,co.TH_CENTER])[co.CPer].plot(marker='.',xscale='log')
def plot_ecoregion( ax_, extent, mega1, plot_box=False, xticks=None, yticks=None, xd=-.3, edgecolor='r', left_lab=False, right_lab=False, top_lab=False, botttom_lab=False, red_rect_extent=None, remove_label_inside_box=False, ): if yticks is None: yticks = [-10, -20, -30] if xticks is None: xticks = [-80, -70, -60] ax = fa.get_ax_bolivia( lola_extent=extent, fig_args={ 'figsize': (3.125, 3.125), 'dpi': 300 }, draw_labels=False, map_line_alpha=.3, plot_cities=False, # chc_lp_legend=False, ax=ax_, xlab_bot=False, ylab_left=False, grid_alpha=0) lo2, lo1, la2, la1 = extent rec = shapely.geometry.Polygon([[lo1, la1], [lo1, la2], [lo2, la2], [lo2, la1], [lo1, la1]]) def _f(p): p1: shapely.geometry.MultiPolygon = p['geometry'] print(p['name']) try: res = p1.intersection(rec) except: try: res = p1.buffer(.01) res = res.intersection(rec) except: res = np.nan return res mm = mega1.copy() mm['geometry'] = mm.apply(_f, axis=1) mm = mm[mm.area > 0] mm['rp'] = mm.representative_point() ax.legend().remove() # plt.show() res = mm.plot(ax=ax, color=mm['color']) if plot_box: add_red_box(ax, edgecolor, red_rect_extent) def _lab(r): if remove_label_inside_box: print('removing') if r["inf_index"] in [10, 21, 36, 24]: return 'pass' t = ax.annotate(f'•{r["inf_index"]}', [r['rp'].x + r['xd'], r['rp'].y + r['yd']], color='k', weight='medium', size=5, zorder=100) # t.set_bbox(dict( # facecolor='white', alpha=0.2, edgecolor='none')) return t mm = mm[mm.area > .5] mm = mm[mm['concur_area'] > .1] mm['xd'] = xd mm['yd'] = 0 b1 = mm['inf_index'].isin([35, 38]) mm = mm[~b1] mm['lab'] = mm.apply(_lab, axis=1) ax.set_xticks(xticks) ax.set_yticks(yticks) left = left_lab right = right_lab top = top_lab, bottom = botttom_lab ax.tick_params( labelleft=left, left=left, labelright=right, right=right, labeltop=top, top=top, labelbottom=bottom, bottom=bottom, )
def plot_pathways(geo_df, lon_range=15, lat_range=13, centroid_to_plot=None, chc_lp_legend=False, ax_bolivia=True, ax=None, min_font_size=5, labs_to_plot='all', background_alpha=0): npdf = geo_df if centroid_to_plot is None: centroid_to_plot = ['LR', 'MR'] if ax is None: ucp.set_dpi(300) f_width = 7.25 figsize = (f_width, f_width / 1.6) _, ax = plt.subplots(subplot_kw=dict(projection=crt.crs.PlateCarree()), figsize=figsize) ax: plt.Axes if ax_bolivia: fa.get_ax_bolivia( ax=ax, plot_cities=False, map_res='50m', lake_face_color='none', map_line_alpha=.5, chc_lp_legend=chc_lp_legend, grid_alpha=0, draw_labels=False, xlab_top=False, xlab_bot=False, ylab_left=False, ylab_right=False, ) else: fa.get_ax_lapaz(ax=ax, plot_cities=False, lake_face_color='none', map_line_alpha=.5, chc_lp_legend=chc_lp_legend, grid_alpha=0, draw_labels=False, y_left_lab=False) npdf['text_xy'] = [[[0, 0]]] * len(npdf) npdf.loc['07_LR', 'text_xy'] = [[[-5, -12]]] npdf.loc['08_LR', 'text_xy'] = [[[-5, 7]]] npdf.loc['10_LR', 'text_xy'] = [[[8, 0]]] npdf.loc['11_MR', 'text_xy'] = [[[-13, 7]]] npdf.loc['02_MR', 'text_xy'] = [[[-10, 7]]] npdf.loc['04_MR', 'text_xy'] = [[[-10, 7]]] npdf.loc['05_MR', 'text_xy'] = [[[5, 0]]] npdf.loc['09_MR', 'text_xy'] = [[[-25, -8]]] npdf.loc['08_SM', 'text_xy'] = [[[-25, -10]]] npdf.loc['12_SM', 'text_xy'] = [[[-3, 7]]] npdf.loc['03_SM', 'text_xy'] = [[[5, -4]]] npdf.loc['06_SM', 'text_xy'] = [[[-7, -10]]] npdf.loc['11_SR', 'text_xy'] = [[[-10, 7]]] npdf.loc['02_SR', 'text_xy'] = [[[-3, 7]]] npdf.loc['12_SR', 'text_xy'] = [[[-12, 7]]] npdf.loc['04_SR', 'text_xy'] = [[[4, -10]]] npdf.loc['07_SR', 'text_xy'] = [[[-17, -12]]] npdf.loc['10_SR', 'text_xy'] = [[[-10, 5]]] lrpdf = npdf[npdf['range'].isin(centroid_to_plot)] for l, r in lrpdf.iterrows(): ax.scatter(r['lon'], r['lat'], s=40, c=[r['range_color']], marker=r['range_marker'], zorder=20, edgecolors=['k'], linewidth=1) if labs_to_plot == 'all': lab_lrpdf = lrpdf else: lab_lrpdf = npdf[npdf['range'].isin(labs_to_plot)] for l, r in lab_lrpdf.iterrows(): ax.annotate( r.name, xy=r[['lon', 'lat']], xytext=r['text_xy'][0], textcoords='offset points', zorder=12, backgroundcolor=[1, 1, 1, background_alpha], # bbox=dict(boxstyle="round", # alpha=0, # linewidth=0, # facecolor='w' # ), alpha=.5, fontsize=min_font_size, arrowprops=dict(arrowstyle='-', alpha=.5)) # ax.set_ylim(-15,15LR) import cartopy.mpl.geoaxes ax: crt.mpl.geoaxes.GeoAxesSubplot _xx, _yy = lon_range, lat_range extent = get_extent(_xx, _yy) ax.set_extent(extent, crt.crs.PlateCarree()) # plt.show() return ax
def plot_pathways(npdf, dac_sum, conc_name, lon_range=15, lat_range=13, centroid_to_plot=None, chc_lp_legend=False, q_level=.8, ax_bolivia=True, ax=None, min_fs=5, add_patch=True, labs_to_plot='all', background_alpha=0): if centroid_to_plot is None: centroid_to_plot = ['LR', 'MR'] if ax is None: ucp.set_dpi(300) f_width = 7.25 figsize = (f_width, f_width / 1.6) _, ax = plt.subplots(subplot_kw=dict(projection=crt.crs.PlateCarree()), figsize=figsize) ax: plt.Axes if ax_bolivia: fa.get_ax_bolivia( ax=ax, plot_cities=False, map_res='50m', lake_face_color='none', map_line_alpha=.5, chc_lp_legend=chc_lp_legend, grid_alpha=0, draw_labels=False, ) else: fa.get_ax_lapaz(ax=ax, plot_cities=False, lake_face_color='none', map_line_alpha=.5, chc_lp_legend=chc_lp_legend, grid_alpha=0, draw_labels=False, y_left_lab=False) # gpdf = npdf.groupby('range') for l, r in npdf.iterrows(): _q = q_level l = r['cluster_i'] res = get_res_quan(dac_sum, l, _q, conc_name=conc_name) pols = res.apply(lambda r: sh_polygon_from_row(r), axis=1) u = cascaded_union(pols) patch = PolygonPatch(u, alpha=.7, facecolor=r['c6_colors'], edgecolor=r['c6_colors'], linewidth=1, zorder=11) if add_patch: ax.add_patch(patch) npdf['text_xy'] = [[[0, 0]]] * len(npdf) npdf.loc['07_LR', 'text_xy'] = [[[-5, -12]]] npdf.loc['08_LR', 'text_xy'] = [[[-5, 7]]] npdf.loc['10_LR', 'text_xy'] = [[[8, 0]]] npdf.loc['11_MR', 'text_xy'] = [[[-13, 7]]] npdf.loc['02_MR', 'text_xy'] = [[[-10, 7]]] npdf.loc['04_MR', 'text_xy'] = [[[-10, 7]]] npdf.loc['05_MR', 'text_xy'] = [[[5, -10]]] npdf.loc['09_MR', 'text_xy'] = [[[-25, -8]]] npdf.loc['08_SM', 'text_xy'] = [[[-23, -15]]] npdf.loc['12_SM', 'text_xy'] = [[[-3, 7]]] npdf.loc['03_SM', 'text_xy'] = [[[5, -4]]] npdf.loc['06_SM', 'text_xy'] = [[[-7, -10]]] npdf.loc['11_SR', 'text_xy'] = [[[-10, 7]]] npdf.loc['02_SR', 'text_xy'] = [[[-3, 7]]] npdf.loc['12_SR', 'text_xy'] = [[[-12, 7]]] npdf.loc['04_SR', 'text_xy'] = [[[4, -10]]] npdf.loc['07_SR', 'text_xy'] = [[[-17, -12]]] npdf.loc['10_SR', 'text_xy'] = [[[-30, 0]]] _x = npdf[co.R_CENTER] * np.sin(npdf[co.TH_CENTER]) _y = npdf[co.R_CENTER] * np.cos(npdf[co.TH_CENTER]) npdf['lat'] = _y + co.CHC_LAT npdf['lon'] = _x + co.CHC_LON lrpdf = npdf[npdf['range'].isin(centroid_to_plot)] for l, r in lrpdf.iterrows(): ax.scatter(r['lon'], r['lat'], s=40, c=[r['range_color']], marker=r['range_marker'], zorder=20, edgecolors=['k'], linewidth=1) if labs_to_plot == 'all': lab_lrpdf = lrpdf else: lab_lrpdf = npdf[npdf['range'].isin(labs_to_plot)] for l, r in lab_lrpdf.iterrows(): ax.annotate( r.name, xy=r[['lon', 'lat']], xytext=r['text_xy'][0], textcoords='offset points', zorder=12, backgroundcolor=[1, 1, 1, background_alpha], # bbox=dict(boxstyle="round", # alpha=0, # linewidth=0, # facecolor='w' # ), alpha=.5, fontsize=min_fs, arrowprops=dict(arrowstyle='-', alpha=.5)) # ax.set_ylim(-15,15LR) import cartopy.mpl.geoaxes ax: crt.mpl.geoaxes.GeoAxesSubplot _xx, _yy = lon_range, lat_range extent = get_extent(_xx, _yy) ax.set_extent(extent, crt.crs.PlateCarree()) # plt.show() return ax
pat = Path(co.tmp_data_path) / 'new_log_pol_ds_asl_v01.nc' # %% ds = xr.open_dataset(pat) # %% ds # %% ds['CONC'][{co.RL: 10}].sum(co.ZM).plot(y=co.R_CENTER, x=co.TH_CENTER) # %% da = ds.loc[{co.RL: '2018-01-10 15'}] # %% ax = fa.get_ax_bolivia() fa.logpolar_plot(da.sum(co.ZM), ax=ax) # %% da # %% da # %% da = ds.loc[{co.RL: slice('2018-01-10 21', '2018-01-11 06')}] da['dis'] = da[co.R_CENTER] * 100 da = da.assign_coords(dis=da['dis']) da['CONC'].sum(co.TH_CENTER).\ plot( x='dis',figsize=(20,5),
def clus_plot( i_lab, ds: xr.Dataset, conc_lab=None, ds_lab=None, figure_size=15, dpi=400, fig_title: str = None, conc_lab_ts=None, df_prop=None ): if conc_lab is None: conc_lab = ds.attrs['chosen_smooth'] if conc_lab_ts is None: conc_lab_ts = conc_lab r_dis_km: xr.DataArray = ds[co.R_CENTER] * 100 r_dis_km = r_dis_km.assign_attrs({ 'units': 'km', 'long_name': 'radial distance from CHC' }) # return r_dis_km ds = ds.assign_coords(**{R_DIS_KM: r_dis_km}) if ds_lab is None: ds_lab = ds[[conc_lab_ts, conc_lab]].where(ds['lab'] == i_lab) ds_lab = ds_lab.assign_coords(**{R_DIS_KM: r_dis_km}) # print(ds_lab.attrs) cols = 10 rows = 10 f_len = figure_size f: plt.Figure = plt.figure( figsize=(f_len, cols / rows * f_len), dpi=dpi ) xn = 2 yn = 4 xp = .07 yp = .05 ww = (1 - xp * 3) / xn hh = (1 - yp * 5) / yn # yy = .29 # xx = .4 # xxL = .55 # ypos = .35 l_lpb = ((2 * xp) + ww, (2 * yp) + hh, .8 * ww, hh) l_bol = ((2 * xp) + ww, yp, .8 * ww, hh) l_ts = (xp, 1 - yp - hh, 1 - 2 * xp, hh) l_per_inf = (xp, (3 * yp) + (2 * hh), ww, hh) l_far = (xp, yp, 1.2 * ww, hh) l_zoom = (xp, 2 * yp + hh, 1.2 * ww, hh) ax_vertical_far_: plt.Axes = f.add_axes(l_far) da_lab = ds_lab[conc_lab] da_lab.load() plot_vertical_ax(ax_vertical_far_, conc_lab, ds, da_lab) ax_vertical_far_.scatter(0, 5240, c='blue', label='CHC') ax_vertical_far_.legend() ax_vertical_far_.grid(True) ax_vertical_far_.set_axisbelow(False) ax_vertical_zoom = f.add_axes(l_zoom) plot_vertical_ax(ax_vertical_zoom, conc_lab, ds, da_lab, xlim=(0, 200)) ax_vertical_zoom.scatter(0, 5240, c='blue', label='CHC') ax_vertical_zoom.legend() ax_vertical_zoom.grid(True) ax_vertical_zoom.set_axisbelow(False) carree = crt.crs.PlateCarree() ax_lpb: cartopy.mpl.geoaxes.GeoAxesSubplot = \ f.add_axes(l_lpb, projection=carree) cc_ = da_lab.sum([co.RL, co.ZM], keep_attrs=True) ax_lpb = fa.get_ax_lapaz(ax=ax_lpb) print(cc_.attrs) fa.logpolar_plot(cc_, name=conc_lab, ax=ax_lpb) ax_bol = f.add_axes(l_bol, projection=carree) lo_la_bol_range = 15 lo_la_limits = [ co.CHC_LON - lo_la_bol_range, co.CHC_LON + lo_la_bol_range, co.CHC_LAT - lo_la_bol_range, co.CHC_LAT + lo_la_bol_range, ] ax_bol = fa.get_ax_bolivia(ax=ax_bol, lola_extent=lo_la_limits) fa.logpolar_plot(cc_, name=conc_lab, ax=ax_bol) # noinspection PyUnusedLocal ax_ts = f.add_axes(l_ts) plot_lab_time_series(da_lab=ds_lab[conc_lab_ts], ax_ts=ax_ts) ax_per_inf = f.add_axes(l_per_inf) if df_prop is not None: plot_cluster_summary_figure( df_prop, 'SRR [%]', 'distance from CHC [km]', # save_fig=True, fig_save_name='dis_vs_srr_influence.pdf', xy_locs=([-30, 5], [0, 9], [500, 11], [950, 9]), y_range=(0, 13), add_vertical_lines=True, add_cluster_group_label=False, ax=ax_per_inf ) y = df_prop.set_index('cluster_i')['SRR [%]'][i_lab] x = df_prop.set_index('cluster_i')['distance from CHC [km]'][i_lab] # ax_per_inf.scatter(x,y,c='k',s=10,marker='o') ax_per_inf.scatter(x, y, s=200, marker='o', facecolors='none', edgecolors='k') # todo fix this else: plot_concentration_influence_div_by_cluster( ds=ds, conc_lab=conc_lab, i_lab=i_lab, ax=ax_per_inf ) plt.show() if fig_title is None: f.suptitle(f'cluster: {i_lab}', y=.95) else: f.suptitle(fig_title, y=1) f.tight_layout() log.ger.debug('show plot') f.show() return f