def load_and_plot_diffs(varl, case_ctrl, case_other, start_time, end_time, pressure_coords=True, relative=False, cbar_orient='vertical', asp_ratio=2, subfig_size=3, ncol=None, ylim=None, yscale='log', norm=None ): if ylim is None: ylim = [1e3, 100] cases_dict = get_averaged_fields.get_levlat_cases(cases, varl, start_time, end_time, pressure_adjust=pressure_coords) _nv = len(varl) if ncol is None: if _nv > 3: ncol = 2 else: ncol = 1 # noinspection PyUnresolvedReferences nrow = int(np.ceil(_nv / ncol)) figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow] # noinspection PyTypeChecker fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True) for ax, var in zip(axs.flat, varl): plot_levlat_diff(var, case_ctrl, case_other, cases_dict, cbar_orientation=cbar_orient, relative=relative, ylim=ylim, yscale=yscale, ax=ax, norm=norm) return axs
def load_and_plot_diffs_more_cases(varl, cases, case_oth, startyear, endyear, pressure_adjust=pressure_adjust, relative=False, cbar_orientation='vertical', asp_ratio=2, subfig_size=3, ylim=None, yscale='log', cbar_eq=True, norm=None): if ylim is None: ylim = [1e3, 100] imp_cases = list(set(cases).union({case_oth})) print(imp_cases) cases_dic = get_averaged_fields.get_levlat_cases(imp_cases, varl, startyear, endyear, pressure_adjust=pressure_adjust) ncol = len(cases) nrow = len(varl) figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow] # noinspection PyTypeChecker fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True) for j, var in enumerate(varl): saxs = axs[j, :] levlat_more_cases_var(var, case_oth, cases, cases_dic, cbar_eq, cbar_orientation, saxs, norm, relative, ylim, yscale) return axs
def _plt_2dhist(ds_diff, xvar, yvar, nr_bins=40, yscale='symlog', xscale='log', xlim=[1e-6, 1e-2], ylim=[5., 1e3], ax=None): """ xvar = f'NUCLRATE_{case_orig}' yvar='NCONC01' xlim = [1e-6,1e-2] ylim=[1,1e3] nr_bins = 40 yscale='symlog' xscale='log' """ print(xlim) print(ylim) varList = [ xvar, yvar ] #f'NUCLRATE_{case_orig}',f'logNUCLRATE_{case_orig}',f'logSOA_LV_{case_orig}',f'logH2SO4_{case_orig}',f'logNCONC01_{case_orig}',f'logN_AER_{case_orig}',f'N_AER_{case_orig}',f'H2SO4_{case_orig}','NCONC01'] dims = tuple(ds_diff[varList].dims) _ds_s = ds_diff[varList].stack(ind=dims) #('lat','lon','lev','time')) ybins = mk_bins(ylim[0], vmax=ylim[1], nr_bins=nr_bins, scale=yscale) xbins = mk_bins(xlim[0], vmax=xlim[1], nr_bins=nr_bins, scale=xscale) data = _ds_s.to_dataframe() lim = 0 #data = -data[(data['NCONC01']<lim)]# | (data['NCONC01']>=lim)] x = data[xvar] #f'NUCLRATE_{case_orig}'] y = data[yvar] #'NCONC01'] if ax is None: fig, ax = plt.subplots(1) h = ax.hist2d(x, y, bins=[xbins, ybins], cmap='Reds') #,extent=[-3,3,-300,20],yscale='symlog') plt.colorbar(h[3], ax=ax, format=OOMFormatter(4, mathText=False)) #cb = fig.colorbar(c, ax=ax) if yscale == 'symlog': ax.set_yscale('symlog', linthreshy=ylim[0], linscaley=ylim[0] / 10, subsy=[2, 3, 4, 5, 6, 7, 8, 9]) yt = ax.get_yticks() ml = np.abs(yt[yt != 0]).min() ytl = yt ytl[(yt == ml) | (yt == -ml)] = None ax.set_yticks(ticks=yt) #[y for y in yt if y!=0])#, ax.set_yticklabels(ytl) #[-1e2,-1e1,-1e0,1e0,1e1,1e2]) elif yscale == 'log': print('set log scale') ax.set_yscale( 'log' ) #, linthreshy=ylim[0], linscaley=ylim[0]/10,subsy=[2,3,4,5,6,7,8,9]) #ax.set_yticks([y for y in yt if y!=0])#[-1e2,-1e1,-1e0,1e0,1e1,1e2]) ax.set_xscale('log') return ax
def corr_plt(): # %% var_c = 'AWNC_incld' varl_to = ['NCONC01','NMR01'] cbar_orientation = 'vertical' cases_ctrl = cases_orig case_oth = cases_sec[0] ncol = len(cases_ctrl) nrow = len(varl_to) subfig_size = 2.6 asp_ratio = 1.6 figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow] # noinspection PyTypeChecker fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True) norm_dic = dict( NCONC01=colors.SymLogNorm(vmin=-1e3, vmax=1e3, linthresh=10), NMR01=colors.SymLogNorm(vmin=-10, vmax=10, linthresh=.1), AWNC_incld=colors.SymLogNorm(vmin=-20, vmax=20, linthresh=.1), AREL_incld=colors.SymLogNorm(vmin=-5, vmax=5, linthresh=.1) ) for j, var in enumerate(varl_to): saxs = axs[j, :] for i, case in enumerate(cases_ctrl): ax = saxs[i] _vars = [var, var_c] _ds = cases_dic[case_oth][_vars]- cases_dic[case][_vars] _da_corr = corr(_ds[var],_ds[var_c], dim=['time','lon']) nn_ctrl = get_nice_name_case(case) nn_oth = get_nice_name_case(case_oth) title = f'Correlation $\Delta V = V_x - V_y$),\n x={nn_oth}, y={nn_ctrl}' _da_corr.load() label = f'corr($\Delta${get_fancy_var_name(var)},$\Delta${get_fancy_var_name(var_c)})'#) plt_kwargs ={} plt_kwargs = make_cbar_kwargs(label, plt_kwargs, cbar_orientation) plot_levlat(ax, 'RdBu_r', _da_corr, title, [1e3,200], # cbar_orientation='vertical', # #ax=ax, # #norm=norm_dic[var], # #relative=False, # #ylim=[1e3, 200], yscale='log', **plt_kwargs) for ax in axs.flatten(): ax.set_ylabel('') ax.set_xlabel('') for ax in axs[:, 0]: ax.set_ylabel('Pressure [hPa]') for ax in axs[-1, :]: ax.set_xlabel('Latitude [$^\circ$N]') fig.tight_layout() fn = filen_base + f'corr_NMR_N_clouds_{case_oth}' + '_'.join(cases_ctrl) + f'{startyear}-{endyear}' subp_insert_abc(axs, pos_x=1.1,pos_y=1.1) plt.savefig(fn + '.pdf') plt.savefig(fn + '.png') plt.show()
def plot_seasonal_surface_loc_sizedistributions(cases_sec, cases_orig, from_t, to_t, variables=['dNdlogD'], minDiameter=5., maxDiameter=39.6, resolution='month', history_field='.h0.', figsize= [12,6], locations=constants.collocate_locations.keys()): cl = Sizedistribution s_list = [] for case in cases_sec: s1 = cl(case, from_t, to_t, [minDiameter, maxDiameter], True, resolution, history_field=history_field) s_list.append(s1) for case in cases_orig: s1 = cl(case, from_t, to_t, [minDiameter, maxDiameter], False, resolution, history_field=history_field) s_list.append(s1) cmap_dic = get_cmap_dic(cases_sec+cases_orig) for loc in locations: fig, axs = plt.subplots(2, 2, figsize=figsize) axs = axs.flatten() for s in s_list: ls = variables #if s.isSectional: # ls = ls + ['dNdlogD_sec'] s.plot_location(variables=ls, c=cmap_dic[s.case_name], axs=axs, loc=loc, ylim=[10,1e4]) fig.tight_layout() savepath = constants.paths_plotsave['sizedist'] +'/season/' _cas = '_'.join(cases_sec) + '_'+'_'.join(cases_orig) savepath = savepath +loc+ _cas + 'mean_%s-%s_%s.png'%(from_t, to_t, resolution) make_folders(savepath) plt.savefig(savepath, dpi=200) plt.show()
ax=ax, norm=norm, **cba_kwargs) # %% varlist = ['NCONC01', 'NMR01', 'AWNC_incld', 'AREL_incld'] cbar_orientation = 'vertical' cases_ctrl = cases_orig case_oth = cases_sec[0] ncol = len(cases_ctrl) nrow = len(varlist) subfig_size = 2.6 asp_ratio = 1.6 figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow] # noinspection PyTypeChecker fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True) norm_dic = dict( NCONC01=colors.SymLogNorm(vmin=-1e3, vmax=1e3, linthresh=10), NMR01=colors.SymLogNorm(vmin=-10, vmax=10, linthresh=1),# linscale=.5), AWNC_incld=colors.SymLogNorm(vmin=-20, vmax=20, linthresh=1), AREL_incld=colors.SymLogNorm(vmin=-5, vmax=5, linthresh=.1) ) cases_dic = get_averaged_fields.get_levlat_cases(cases, varlist, startyear, endyear, pressure_adjust=pressure_adjust) for j, var in enumerate(varlist): saxs = axs[j, :] levlat_more_cases_var(var, case_oth, cases_ctrl, cases_dic, cbar_eq=True, cbar_orientation='vertical', axs=saxs,
# %% import seaborn as sns # %% import importlib as il from useful_scit.util import conditional_stats il.reload(conditional_stats) varList = ['H2SO4', 'SOA_LV', 'NCONC01'] varList = ['N_AER', 'GR', 'NCONC01'] sec_sub = cases_dic[case_sec][varList].stack(ind=('lat', 'lon', 'lev', 'time')) # #sec_sub = sec_sub nosec_sub = cases_dic[case_orig][varList].stack(ind=('lat', 'lon', 'lev', 'time')) fig, axs = plt.subplots(3, 2, figsize=[10, 10]) axs = axs.flatten() df, pl_xr_ns, kwargs, xedges, yedges = conditional_stats.plot_cond_statistic( nosec_sub, varList, axs[0], quant=0.1, scale='log', stat='mean', plt_title='Mean Non sectional', cscale='log') df, pl_xr_s, kwargs, xedges, yedges = conditional_stats.plot_cond_statistic( sec_sub, varList, axs[1], quant=0.1,
suptit = f'{fvar_diff}$(m_1)-${fvar_diff}$(m_2)$ vs. $X(m_2)$ \n for $m_1=${get_nice_name_case(case_sec)}, $m_2=${get_nice_name_case(case_base)}' fig.subplots_adjust(hspace=.5, wspace=0.1) #,top=0.8, ) stit = fig.suptitle(suptit, fontsize=12, y=.98) return stit # %% [markdown] # # Difference: # # %% [markdown] # ## Main plot: below 100 hPa: # %% fig, axs = plt.subplots(3, 2, figsize=[6.4, 7.1], sharey=True) #, constrained_layout=True) var_xl = ['NUCLRATE', 'GR', 'H2SO4', 'SOA_LV', 'NCONC01', 'COAGNUCL'] lev_min = 100. _ds = ds_diff.sel(lev=slice(lev_min, None)) var_diff = 'NCONC01' xlims = { 'NUCLRATE': [1.e-6, 10], 'H2SO4': [1.e-3, 1], 'SOA_LV': [1.e-5, 1], 'GR': [1.e-3, 1], 'N_AER': [1e0, 1e4], 'NCONC01': [5e-1, 1e3], 'COAGNUCL': [1e-5, .1], } stit = _plt_tmp(_ds, axs, var_xl, var_diff, xlims)
def corr_plt(var_c=None, varl_to=None,cases_ctrl=None, case_oth = None): # %% if var_c is None: var_c = 'AWNC_incld' if varl_to is None: varl_to = ['NCONC01','NMR01'] cbar_orientation = 'vertical' if cases_ctrl is None: cases_ctrl = cases_orig if case_oth is None: case_oth = cases_sec[0] ncol = len(cases_ctrl) nrow = len(varl_to) subfig_size = 2.5 asp_ratio = 1.6 figsize = [subfig_size * ncol * asp_ratio, subfig_size * nrow] # noinspection PyTypeChecker fig, axs = plt.subplots(nrow, ncol, figsize=figsize, sharex=True, sharey=True) for j, var in enumerate(varl_to): saxs = axs[j, :] for i, case in enumerate(cases_ctrl): ax = saxs[i] _vars = [var, var_c] _ds = cases_dic[case_oth][_vars]- cases_dic[case][_vars] _da_corr = corr(_ds[var],_ds[var_c], dim=['time','lon']) nn_ctrl = get_nice_name_case(case) nn_oth = get_nice_name_case(case_oth) title =f'x={nn_oth}, y={nn_ctrl}'# f'Correlation $\Delta V = V_x - V_y$),\n x={nn_oth}, y={nn_ctrl}' _da_corr.load() label = f'corr($\Delta${get_fancy_var_name(var)},$\Delta${get_fancy_var_name(var_c)})'#) plt_kwargs ={} plt_kwargs = make_cbar_kwargs(label, plt_kwargs, cbar_orientation) plot_levlat(ax, 'RdBu_r', _da_corr, title, [1e3,200], # cbar_orientation='vertical', # #ax=ax, # #norm=norm_dic[var], # #relative=False, # #ylim=[1e3, 200], yscale='log', **plt_kwargs) ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0f')) ax.yaxis.set_minor_formatter(mtick.FormatStrFormatter('%.0f')) title = f'Correlations $\Delta V = V_x - V_y$'#' x={nn_oth}, y={nn_ctrl}' stit = plt.suptitle(title,y = 1.03) for ax in axs.flatten(): ax.set_ylabel('') ax.set_xlabel('') for ax in axs[:, 0]: ax.set_ylabel('Pressure [hPa]') for ax in axs[-1, :]: ax.set_xlabel('Latitude [$^\circ$N]') fig.tight_layout() fn = filen_base + f'corr_NMR_N_clouds_{var_c}{case_oth}' + '_'.join(cases_ctrl) + f'{startyear}-{endyear}' subp_insert_abc(axs, pos_x=1.13,pos_y=1.01) print(fn) plt.savefig(fn + '.pdf', bbox_extra_artists=(stit,),bbox_inches='tight') plt.savefig(fn + '.png',bbox_extra_artists=(stit,),bbox_inches='tight') plt.show()
case = cases_sec[1] s2 = cl(case, from_t, to_t, [minDiameter, maxDiameter], True, 'month', history_field='.h0.') #a2 = s1.get_collocated_dataset() from useful_scit.plot import get_cmap_dic cmap_dic = get_cmap_dic(cases_sec + cases_orig) for loc in constants.collocate_locations.keys(): print(loc, '***********************************************') fig, axs = plt.subplots(2, 2) axs = axs.flatten() for s in s_list: ls = ['dNdlogD_mode01'] if s.isSectional: ls = ls + ['dNdlogD_sec'] a = s.get_collocated_dataset(variables=ls) print(a) b = a['dNdlogD_mode01'] # + a['dNdlogD_sec'] c = b.mean('lev').groupby('time.season').mean('time') for seas, ax in zip(c['season'].values, axs): _da = c.sel(season=seas, location=loc) _da.plot(xscale='log',