def map_recovery_time(myC,HAZ,RP=[50,200],RECO=['50','75','90'],drop_spots=None,_mapres=2000,special_event=None): df = pd.read_csv('../output_country/'+myC+'/time_to_recovery_no.csv') # hack #if myC == 'MW': # df.loc[df.district=='Blantyre'] = df.loc[(df.district=='Blantyre')|(df.district=='Blantyre City')].sum() # df.loc[df.district=='Lilongwe'] = df.loc[(df.district=='Lilongwe')|(df.district=='Lilongwe City')].sum() # df.loc[df.district=='Mzimba'] = df.loc[(df.district=='Mzimba')|(df.district=='Mzuzu City')].sum() # df.loc[df.district=='Zomba Non-City'] = df.loc[(df.district=='Zomba Non-City')|(df.district=='Zomba City')].sum() # df = df_prov.drop(['Blantyre City','Lilongwe City', 'Mzuzu City', 'Zomba City'],axis=0) # Look for the map (svg) file here svg_file = get_svg_file(myC) _pop = pd.read_csv('../intermediate/'+myC+'/hazard_ratios.csv') _pop = _pop.set_index([get_economic_unit(myC),'hazard','rp']) _pop_event = _pop['pcwgt'].sum(level=_pop.index.names).to_frame(name='pop') _pop_event['fa'] = _pop['fa'].mean(level=_pop.index.names) _pop_event['Naff'] = _pop_event[['pop','fa']].prod(axis=1) _pop_event = _pop_event.reset_index().set_index(get_economic_unit(myC)) if special_event and special_event.lower() == 'idai': df = pd.merge(df.reset_index(),_pop_event.reset_index(),on=['district','hazard','rp']) for _haz in [HAZ]: for _rp in RP: for _reco in RECO: _ = df.loc[(df.hazard == _haz)&(df.rp == _rp)].set_index(get_economic_unit(myC)) if special_event and special_event.lower() == 'idai': _ = _.loc[_['fa']!=0] else: _.loc[_['time_recovery_'+_reco]==-1,'time_recovery_'+_reco] = 10 __pop_event = _pop_event.loc[(_pop_event.hazard == _haz)&(_pop_event.rp == _rp)] _mean = str(round((_['time_recovery_'+_reco]*__pop_event['Naff']).sum()/__pop_event['Naff'].sum(),1)) _label = (('Time to reconstruct '+_reco+'% of\nassets destroyed by '+haz_dict[_haz]+' [years]\nAverage = '+_mean+' years') if special_event and special_event.lower() == 'idai' else ('Time to reconstruct '+_reco+'% of assets destroyed' +'\nby '+str(_rp)+'-year '+haz_dict[_haz].lower()+' [years]' +'\nNational avg. = '+_mean+' years')) try: make_map_from_svg( _['time_recovery_'+_reco], svg_file, outname=myC+'_time_to_recover_'+_reco+'pct_'+_haz+str(_rp), color_maper=plt.cm.get_cmap('Purples'), label=_label, new_title='', do_qualitative=True, drop_spots=['Jaffna','Matara','Kilinochchi'], res=_mapres) except: pass purge('img/','map_of_*.png') purge('img/','legend_of_*.png') purge('img/','map_of_*.svg') purge('img/','legend_of_*.svg')
def plot_relative_losses(myCountry, aProv, aDis, anRP, iah): economy = get_economic_unit(myCountry) iah = iah.loc[iah.affected_cat == 'a'] iah = iah.reset_index().set_index('quintile').sort_index() _poor = 100. * iah.loc[( (iah.ispoor == 1) & (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP)), ['dk0', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[( (iah.ispoor == 1) & (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP)), ['k', 'pcwgt_no']].prod(axis=1).sum() _nonpoor = 100 * iah.loc[( (iah.ispoor == 0) & (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP)), ['dk0', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[( (iah.ispoor == 0) & (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP)), ['k', 'pcwgt_no']].prod(axis=1).sum() print(aProv, aDis, anRP) print('Poor:', _poor) print('Non-poor:', _nonpoor) print('Ratio:', _poor / _nonpoor, '\n\n')
def run_urban_plots(myC,df): # use isrural to sort households in Bolivia global _upper_cut _upper_cut = 1.5 #times poverty_line # yor_pal = sns.color_palette('tab20b', n_colors=20) # global _colUS; global _colRS global _colUP; global _colRP global _colUN; global _colRN global _colUW; global _colRW _colUS = yor_pal[12]; _colRS = yor_pal[15] _colUP = yor_pal[8]; _colRP = yor_pal[11] _colUN = yor_pal[4]; _colRN = yor_pal[7] _colUW = yor_pal[0]; _colRW = yor_pal[3] # global _colUV; global _colRV _colUV = yor_pal[0]; _colRV = yor_pal[3] # global _alphaU; global _alphaR _alphaU = 0.50; _alphaR = 0.8 # global _e _e = get_economic_unit(myC) if 'isrural' not in df.columns: return False else: # plot poverty gap, by urban/rural, & by department df = df.reset_index().set_index([_e,'ispoor','isrural'])[['pcwgt','totper','c','pcsoc','has_ew','pov_line','sub_line','issub']] # social_scatter(myC,df,'rel') social_scatter(myC,df,'abs') # poverty_gap(myC,df) # for plot_rural in [True, False]: populations(myC,df,'rel',plot_rural) populations(myC,df,'abs',plot_rural) # # this code shouldn't be here! # we're analyzing model results in a function that gets called in gather_data # but it's easiest... #try: model_results_plots(myC,'assets','abs',('PF','aal'),redo_intermediate=True) model_results_plots(myC,'assets','rel',('PF','aal')) model_results_plots(myC,'assets','tot',('PF','aal')) model_results_plots(myC,'wellbeing','abs',('PF','aal')) model_results_plots(myC,'wellbeing','rel',('PF','aal')) model_results_plots(myC,'wellbeing','tot',('PF','aal')) model_results_plots(myC,'resilience','',('PF','aal')) model_results_plots(myC,'assets','abs',('PF',50),redo_intermediate=True) model_results_plots(myC,'assets','rel',('PF',50)) model_results_plots(myC,'assets','tot',('PF',50)) model_results_plots(myC,'wellbeing','abs',('PF',50)) model_results_plots(myC,'wellbeing','rel',('PF',50)) model_results_plots(myC,'wellbeing','tot',('PF',50)) model_results_plots(myC,'resilience','',('PF',50))
def plot_income_and_consumption_distributions(myC, iah, aReg, aDis, anRP, labels=(False, False, False), currency=''): label_subsistence, label_poverty, label_middleclass = labels iah = iah.reset_index() economy = get_economic_unit(myC) iah = iah.loc[iah.pcwgt_no != 0].copy() iah['pov_line'] = get_poverty_line(myC) try: plt.close('all') except: pass if aReg == 'ompong': reg_crit = "((region=='I - Ilocos')|(region=='II - Cagayan Valley')|(region=='CAR'))" aReg = 'path of Typhoon Mangkhut' else: reg_crit = '(' + economy + '==@aReg)' economy = get_economic_unit(myC) output_plots = os.getcwd() + '/../output_plots/' + myC + '/' # Number of bins in histograms. Ignore the None argument c_bins = [None, 50] # Dictionary for labeling # GLOBAL VARIABLE in new_process_data. haz_dict = { 'SS': 'Storm surge', 'PF': 'Precipitation flood', 'HU': 'Typhoon', 'EQ': 'Earthquake', 'DR': 'Drought', 'FF': 'Fluvial flood', 'CY': 'Cyclone Idai' } simple_plot = True stack_wealthy = True upper_clip = 1E6 if myC == 'PH': if aReg == 'VIII - Eastern Visayas': upper_clip = 1.25E5 # Hack hack hack else: upper_clip = 1.5E5 elif myC == 'FJ': upper_clip = 2E4 elif myC == 'SL': upper_clip = 3.25E5 if aReg == 'Rathnapura': upper_clip = 3.0E5 elif myC == 'MW': if aReg == 'Lilongwe': upper_clip = 4.0E5 else: upper_clip = 2.5E5 elif myC == 'BO': upper_clip = 5E4 elif myC == 'AM': upper_clip = 9E3 elif myC == 'BG': upper_clip = 2E4 elif myC == 'AL': upper_clip = 5.6E3 elif myC == 'RO': upper_clip = 5E4 elif myC == 'GR': upper_clip = 3E4 elif myC == 'TR': upper_clip = 3E4 elif myC == 'HR': upper_clip = 5E4 else: upper_clip = 1E4 sf_x = 1 #if currency.lower() == 'usd': sf_x = get_currency(myC)[2] currency = get_currency(myC)[0] for _fom, _fom_lab in [('c', 'Consumption')]: ax = plt.gca() plt.cla() plt.xlim(0, sf_x * upper_clip) if not stack_wealthy: upper_clip *= 1.1 if currency.lower() != 'usd' and myC == 'PH': plt.xlim([0, 100]) if aReg == 'II - Cagayan Valley' and aDis == 'HU': plt.ylim(0, 400) elif aReg == 'VIII - Eastern Visayas' and aDis == 'HU': plt.ylim(0, 500) elif aReg == 'Rathnapura': plt.ylim(0, 130) #elif aReg == 'Bucharest-Ilfov': plt.ylim(0,220) elif aReg == 'Beni': plt.ylim(0, 40) if aReg == 'Gergharkunik': plt.ylim(0, 25) if aReg == 'Yerevan': plt.ylim(0, 70) if myC == 'BG': plt.ylim(0, 250) if myC == 'GE': plt.ylim(0, 100) if myC == 'GR': plt.ylim(0, 330) if myC == 'TR': plt.ylim(0, 6000) if myC == 'HR': plt.ylim(0, 500) plt.xlabel(_fom_lab + r' (' + currency + ' per person, per year)', labelpad=8, fontsize=8) plt.ylabel('Population' + get_pop_scale_fac(myC)[1], labelpad=8, fontsize=8) if _fom == 'i': plt.title( str(anRP) + '-year ' + haz_dict[aDis].lower() + ' in ' + aReg) # Income/Cons dist immediately after disaster cf_heights, cf_bins = np.histogram( sf_x * iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), _fom + '_pre_reco'].clip(upper=upper_clip), bins=c_bins[1], weights=iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'] / get_pop_scale_fac(myC)[0]) print(aDis, anRP, _fom, (iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), ['c_initial', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'].sum())) print(_fom, ' final -->', (iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), [_fom + '_pre_reco', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'].sum())) if c_bins[0] is None: c_bins = [cf_bins, cf_bins] # Income dist before disaster ci_heights, _bins = np.histogram( sf_x * iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'c_initial'].clip(upper=upper_clip), bins=c_bins[1], weights=iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'] / get_pop_scale_fac(myC)[0]) # Income dist after reconstruction #cf_reco_hgt, _bins = np.histogram(sf_x*iah.loc[iah.eval(reg_crit+'&(hazard==@aDis)&(rp==@anRP)'),'c_post_reco'].clip(upper=upper_clip), bins=c_bins[1], # weights=iah.loc[iah.eval(reg_crit+'&(hazard==@aDis)&(rp==@anRP)'),'pcwgt_no']/get_pop_scale_fac(myC)[0]) sns.despine() plt.gca().grid(False) pre_step = ax.step(c_bins[1][1:], ci_heights, label=aReg + ' - FIES income', linewidth=1.25, color=greys_pal[7]) #leg = ax.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9) plt.ylim(0) if stack_wealthy: pre_ann = plt.annotate( 'Pre-disaster ' + _fom_lab.lower() + '\n(FIES data)', xy=(c_bins[1][-2], ci_heights[-1]), xytext=(c_bins[1][-4], ci_heights[-1] * 1.075), arrowprops=dict( arrowstyle="-", color=greys_pal[8], connectionstyle="angle,angleA=0,angleB=90,rad=5"), annotation_clip=False, size=8, weight='light', ha='right', va='center', color=greys_pal[8]) else: pre_ann = plt.annotate( 'Pre-disaster ' + _fom_lab.lower() + '\n(FIES data)', xy=((c_bins[1][5] + c_bins[1][6]) / 2, ci_heights[5]), xytext=(c_bins[1][8], ci_heights[5] * 1.02), arrowprops=dict( arrowstyle="-", color=greys_pal[8], connectionstyle="angle,angleA=0,angleB=90,rad=5"), annotation_clip=False, size=8, weight='light', ha='left', va='bottom', color=greys_pal[8]) _success = False _counter = 0 while not _success and _counter < 15: try: _fout = output_plots + 'npr_poverty_' + _fom + '_' + aReg.replace( ' ', '').replace('-', '') + '_' + aDis + '_' + str( anRP) + '_' + currency[-3:].lower() + '_1of3.pdf' #ax.get_figure().savefig(_fout,format='pdf',bbox_inches='tight') _success = True except: print( 'no good! try again in plot_income_and_consumption_distributions (1/3-' + str(_counter) + ')') _counter += 1 #ax.step(c_bins[1][:-1], cf_heights, label=aReg+' - post-disaster', facecolor=q_colors[1],alpha=0.45) #ax.bar(c_bins[1][:-1], -(ci_heights-cf_heights), width=(c_bins[1][1]-c_bins[1][0]), align='edge', # label=aReg+' - post-disaster', facecolor=paired_pal[4],edgecolor=None,linewidth=0,alpha=0.65,bottom=ci_heights) ax.bar(c_bins[1][:-1], cf_heights, width=(c_bins[1][1] - c_bins[1][0]), align='edge', label=aReg + ' - post-disaster', facecolor=paired_pal[4], edgecolor=None, linewidth=0, alpha=0.75) #leg = ax.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9) if stack_wealthy: post_ann = plt.annotate( 'Post-disaster ' + _fom_lab.lower() + '\n(modeled)', xy=((c_bins[1][-2] + c_bins[1][-1]) / 1.99, cf_heights[-1] * 0.90), xytext=(c_bins[1][-4], cf_heights[-1] * 0.90), arrowprops=dict(arrowstyle="-", facecolor=greys_pal[8]), annotation_clip=False, size=8, weight='light', ha='right', va='center', color=paired_pal[5]) else: ax.lines.remove(ax.lines[0]) pre_step = ax.step(c_bins[1][1:], ci_heights, label=aReg + ' - FIES income', linewidth=1.0, color=greys_pal[7], alpha=0.65) pre_ann.remove() pre_ann = plt.annotate( 'Pre-disaster ' + _fom_lab.lower() + '\n(FIES data)', xy=((c_bins[1][5] + c_bins[1][6]) / 2, ci_heights[5]), xytext=(c_bins[1][8], ci_heights[5] * 1.02), arrowprops=dict( arrowstyle="-", color=greys_pal[8], connectionstyle="angle,angleA=0,angleB=90,rad=5", alpha=0.65), annotation_clip=False, size=8, weight='light', ha='left', va='bottom', color=greys_pal[8], alpha=0.65) post_ann = plt.annotate( 'Post-disaster ' + _fom_lab.lower() + '\n(modeled)', xy=(c_bins[1][5], 1.1 * cf_heights[6]), xytext=(c_bins[1][9], 1.1 * cf_heights[6]), annotation_clip=False, size=8, weight='light', ha='left', va='center', color=paired_pal[5], arrowprops=dict( arrowstyle="-", color=paired_pal[5], connectionstyle="angle,angleA=0,angleB=90,rad=5")) _success = False _counter = 0 while not _success and _counter < 10: try: _fout = output_plots + 'npr_poverty_' + _fom + '_' + aReg.replace( ' ', '').replace('-', '') + '_' + aDis + '_' + str( anRP) + '_' + currency[-3:].lower() + '_2of3.pdf' #ax.get_figure().savefig(_fout,format='pdf',bbox_inches='tight') _success = True except: print( 'no good! try again in plot_income_and_consumption_distributions (2/3)' ) _counter += 1 # These are done above #plt.annotate('Pre-disaster '+_fom_lab.lower()+'\n(FIES data)',xy=(c_bins[1][-2],ci_heights[-1]),xytext=(c_bins[1][-4],ci_heights[-1]*1.075), # arrowprops=dict(arrowstyle="-",facecolor=greys_pal[8],connectionstyle="angle,angleA=0,angleB=90,rad=5"), # annotation_clip=False,size=7,weight='light',ha='right',va='center',color=greys_pal[8]) #plt.annotate('Post-disaster '+_fom_lab.lower()+'\n(modeled)',xy=((c_bins[1][-2]+c_bins[1][-1])/1.99,cf_heights[-1]*0.90),xytext=(c_bins[1][-4],cf_heights[-1]*0.90), # arrowprops=dict(arrowstyle="-",facecolor=greys_pal[8]),annotation_clip=False,size=7,weight='light',ha='right',va='center',color=paired_pal[5]) if not stack_wealthy: pre_ann.remove() post_ann.remove() #ax.bar(c_bins[1][:-1], cf_reco_hgt, width=(c_bins[1][1]-c_bins[1][0]), label=aReg+' - post-reconstruction', facecolor=q_colors[1],edgecolor=q_colors[1],alpha=0.65) #ax.step(c_bins[1][1:], ci_heights, label=aReg+' - FIES income', linewidth=1.2,color=greys_pal[8]) #if myC_ylim == None: myC_ylim = ax.get_ylim() #plt.ylim(myC_ylim[0],2.5*myC_ylim[1]) # ^ Need this for movie making, but better to let the plot limits float if not #leg = ax.legend(loc='best',labelspacing=0.75,ncol=1,fontsize=9,borderpad=0.75,fancybox=True,frameon=True,framealpha=0.9) #leg.get_frame().set_color('white') #leg.get_frame().set_edgecolor(greys_pal[7]) #leg.get_frame().set_linewidth(0.2) if not simple_plot: ax.annotate('Total asset losses: ' + str( round( sf_x * iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), ['pcwgt_no', 'dk0']].prod(axis=1).sum(), 1)) + currency, xy=(0.03, -0.18), xycoords=leg.get_frame(), size=8, va='top', ha='left', annotation_clip=False, zorder=100) ax.annotate('Reg. well-being losses: ' + str( round( sf_x * iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), ['pcwgt_no', 'dw']].prod(axis=1).sum() / df.wprime.mean(), 1)) + currency, xy=(0.03, -0.50), xycoords=leg.get_frame(), size=8, va='top', ha='left', annotation_clip=False, zorder=100) ax.annotate('Natl. liability: ' + str( round( float(sf_x * public_costs.loc[ (public_costs.contributer != aReg) & (public_costs[economy] == aReg) & (public_costs.hazard == aDis) & (public_costs.rp == anRP), ['transfer_pub']].sum() * 1.E3), 1)) + currency, xy=(0.03, -0.92), xycoords=leg.get_frame(), size=8, va='top', ha='left', annotation_clip=False, zorder=100) ax.annotate('Natl. well-being losses: ' + str( round( sf_x * float(public_costs.loc[ (public_costs.contributer != aReg) & (public_costs[economy] == aReg) & (public_costs.hazard == aDis) & (public_costs.rp == anRP), 'dw_tot_curr'].sum()), 1)) + ',000 ' + currency, xy=(0.03, -1.24), xycoords=leg.get_frame(), size=8, va='top', ha='left', annotation_clip=False, zorder=100) try: net_chg_pov_c = int(iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_pre_reco<=pov_line)' ), 'pcwgt_no'].sum() - iah.loc[ iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_initial<=pov_line)'), 'pcwgt_no'].sum()) net_chg_pov_i = int(iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(i_pre_reco<=pov_line)' ), 'pcwgt_no'].sum() - iah.loc[ iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_initial<=pov_line)'), 'pcwgt_no'].sum()) except: net_chg_pov_c = int(iah.loc[ iah. eval('district==@aReg & hazard==@aDis & c_pre_reco<=pov_line'), 'pcwgt_no'].sum() - iah.loc[iah.eval( 'district==@aReg & hazard==@aDis & c_initial<=pov_line'), 'pcwgt_no'].sum()) net_chg_pov_i = int(iah.loc[ iah. eval('district==@aReg & hazard==@aDis & i_pre_reco<=pov_line'), 'pcwgt_no'].sum() - iah.loc[iah.eval( 'district==@aReg & hazard==@aDis & c_initial<=pov_line'), 'pcwgt_no'].sum()) try: iah['midclass_line_lo'] = get_middleclass_range(myC)[0] iah['midclass_line_hi'] = get_middleclass_range(myC)[1] net_chg_midclass_c = int(iah.loc[iah.eval(reg_crit + ( '&(hazard==@aDis)&(rp==@anRP)&' + '(c_initial>=midclass_line_lo)&(c_pre_reco<midclass_line_lo)') ), 'pcwgt_no'].sum()) net_chg_midclass_i = int(iah.loc[iah.eval(reg_crit + ( '&(hazard==@aDis)&(rp==@anRP)&' + '(c_initial>=midclass_line_lo)&(i_pre_reco<midclass_line_lo)') ), 'pcwgt_no'].sum()) except: net_chg_midclass_c, net_chg_midclass_i = 0, 0 net_chg_pov = int( round( (net_chg_pov_i if _fom == 'i' else net_chg_pov_c) / 100., 0) * 100) net_chg_midclass = int( round((net_chg_midclass_i if _fom == 'i' else net_chg_midclass_c) / 100., 0) * 100) try: net_chg_pov_pct = abs( round( 100. * float(net_chg_pov) / float(iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'].sum()), 1)) except: net_chg_pov_pct = 0 try: _slice = reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_initial>=midclass_line_lo)&(c_initial<midclass_line_hi)' net_chg_midclass_pct = abs( round( 100. * float(net_chg_midclass) / float(iah.loc[iah.eval(_slice), 'pcwgt_no'].sum()), 1)) except: net_chg_midclass_pct = 0 trans = ax.get_xaxis_transform() # x in data units, y in axes fraction mc_anno_y = 0.80 pov_anno_y = 0.99 sub_anno_y = 0.95 anno_y_offset = 0.045 _, mc_anno_y_data = axis_data_coords_sys_transform(ax, 0, mc_anno_y, inverse=False) _, pov_anno_y_data = axis_data_coords_sys_transform(ax, 0, pov_anno_y, inverse=False) _, sub_anno_y_data = axis_data_coords_sys_transform(ax, 0, sub_anno_y, inverse=False) if label_middleclass: middleclass = get_middleclass_range('RO') plt.plot([sf_x * middleclass[0], sf_x * middleclass[0]], [0, mc_anno_y_data], 'k-', lw=1.0, color=greys_pal[8], zorder=100, alpha=0.85, ls=':') #plt.fill_between([sf_x*middleclass[0],sf_x*middleclass[1]],[pov_anno_y_data,pov_anno_y_data],color=greys_pal[2],alpha=0.3) #plt.fill_between([0,sf_x*middleclass[0]],[pov_anno_y_data,pov_anno_y_data],color=greys_pal[2],alpha=0.3) ax.annotate( 'Middle class', xy=(sf_x * (middleclass[0] + 0.1 * iah.pov_line.mean()), mc_anno_y), xycoords=trans, ha='left', va='top', fontsize=9, annotation_clip=False, weight='bold', color=greys_pal[7]) ax.annotate(int_w_commas(net_chg_midclass) + ' drop from middle class\n (' + str(net_chg_midclass_pct) + '% decrease)', weight='light', color=greys_pal[7], xy=(sf_x * (middleclass[0] + 0.1 * iah.pov_line.mean()), mc_anno_y - anno_y_offset), xycoords=trans, ha='left', va='top', fontsize=9, annotation_clip=False) if label_poverty: plt.plot([sf_x * iah.pov_line.mean(), sf_x * iah.pov_line.mean()], [0, pov_anno_y_data], 'k-', lw=1.0, color=greys_pal[8], zorder=100, alpha=0.85, ls=':') ax.annotate('Poverty line', xy=(sf_x * 1.1 * iah.pov_line.mean(), pov_anno_y), xycoords=trans, ha='left', va='top', fontsize=9, annotation_clip=False, weight='bold', color=greys_pal[7]) ax.annotate('Increase of ' + int_w_commas(net_chg_pov) + ' (' + str(net_chg_pov_pct) + '% of regional pop.)\n in ' + _fom_lab.lower() + ' poverty', weight='light', color=greys_pal[7], xy=(sf_x * 1.1 * iah.pov_line.mean(), pov_anno_y - anno_y_offset), xycoords=trans, ha='left', va='top', fontsize=9, annotation_clip=False) sub_line, net_chg_sub = (None if not label_subsistence else get_subsistence_line(myC)), None if sub_line is not None: net_chg_sub = int( round((iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_pre_reco<=@sub_line)' ), 'pcwgt_no'].sum() - iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_initial<=@sub_line)'), 'pcwgt_no'].sum()) / 100., 0) * 100) if _fom == 'i': net_chg_sub = int( round((iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(i_pre_reco<=@sub_line)' ), 'pcwgt_no'].sum() - iah.loc[iah.eval( reg_crit + '&(hazard==@aDis)&(rp==@anRP)&(c_initial<=@sub_line)'), 'pcwgt_no'].sum()) / 100., 0) * 100) try: net_chg_sub_pct = round( 100. * float(net_chg_sub) / float(iah.loc[iah.eval(reg_crit + '&(hazard==@aDis)&(rp==@anRP)'), 'pcwgt_no'].sum()), 1) except: net_chg_sub_pct = 0 plt.plot([sf_x * sub_line, sf_x * sub_line], [0, sub_anno_y_data], 'k-', lw=1.0, color=greys_pal[8], zorder=100, alpha=0.85, ls=':') ax.annotate('Subsistence line', xy=(sf_x * 1.1 * sub_line, sub_anno_y), xycoords=trans, ha='left', va='top', color=greys_pal[7], fontsize=9, annotation_clip=False, weight='bold') ax.annotate('Increase of ' + int_w_commas(net_chg_sub) + ' (' + str(net_chg_sub_pct) + '% of regional pop.)\n in ' + _fom_lab.lower() + ' subsistence', weight='light', color=greys_pal[7], xy=(sf_x * 1.1 * sub_line, sub_anno_y - anno_y_offset), xycoords=trans, ha='left', va='top', fontsize=9, annotation_clip=False) #print(aReg,aDis,anRP,net_chg_pov,'people into poverty &',net_chg_sub,'into subsistence') fig = ax.get_figure() _success = False _counter = 0 while not _success and _counter < 4: try: _fout = output_plots + 'npr_poverty_' + _fom + '_' + aReg.replace( ' ', '').replace('-', '') + '_' + aDis + '_' + str( anRP) + '_' + currency[-3:].lower() + '.pdf' fig.savefig(_fout, format='pdf', bbox_inches='tight') plt.clf() plt.close('all') _success = True print('wrote ' + aReg + '_poverty_' + _fom + '_' + aDis + '_' + str(anRP) + '.pdf') except: print( 'no good! try again in plot_income_and_consumption_distributions' ) _counter += 1
def plot_impact_by_quintile(myCountry, aProv, aDis, anRP, iah, my_PDS='no', currency='USD'): iah = iah.loc[iah.affected_cat == 'a'] output_plots = '../output_plots/' + myCountry + '/' economy = get_economic_unit(myCountry) plt.figure(1) ax = plt.subplot(111) plt.figure(2) ax2 = plt.subplot(111) _curr = 1 _curr_sf = 1E-3 _curr_sf_str = ',000 ' if currency == 'USD': _curr = get_currency(myCountry)[2] _curr_sf = 1 _curr_sf_str = '' for myQ in range(1, 6): #nQuintiles #print(aProv,aDis,anRP,'shape:',iah.loc[(iah[economy]==aProv)&(iah.hazard==aDis)&(iah.rp==anRP)&(iah.quintile==myQ),'pcwgt_no'].shape[0]) k = _curr * _curr_sf * (0.01 * iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['k', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_no'].sum()) dk = _curr * _curr_sf * (iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['dk0', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_no'].sum()) dc = _curr * _curr_sf * (iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['dc_pre_reco', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_no'].sum()) dw = _curr * _curr_sf * (iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['dw_no', 'pcwgt_no']].prod(axis=1).sum() / iah.loc[ (iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_no'].sum()) pds_nrh = _curr * _curr_sf * ( iah.loc[(iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['net_help_received_' + my_PDS, 'pcwgt_' + my_PDS]].prod(axis=1).sum() / iah.loc[(iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_' + my_PDS].sum()) pds_dw = _curr * _curr_sf * ( iah.loc[(iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), ['dw_' + my_PDS, 'pcwgt_' + my_PDS]].prod(axis=1).sum() / iah.loc[(iah[economy] == aProv) & (iah.hazard == aDis) & (iah.rp == anRP) & (iah.quintile == myQ), 'pcwgt_' + my_PDS].sum()) pds2_dw = _curr * 0 pds3_dw = _curr * 0 ax.bar([6 * ii + myQ for ii in range(1, 5)], [dk, dw, pds_nrh, pds_dw], color=q_colors[myQ - 1], alpha=0.7, label=q_labels[myQ - 1]) #np.savetxt('/Users/brian/Desktop/BANK/hh_resilience_model/output_plots/PH/dk_dc_dw_pds_'+aProv+'_'+aDis+'_'+str(anRP)+'_Q'+str(myQ)+'.csv',[dk,dc,dw,pds_nrh,pds_dw],delimiter=',') if myQ == 1: ax2.bar([0], [0], color=[q_colors[0]], alpha=0.7, label='No post-disaster support') ax2.bar([0], [0], color=[q_colors[2]], alpha=0.7, label='80% of avg Q1 losses covered for Q1') ax2.bar([0], [0], color=[q_colors[3]], alpha=0.7, label='80% of avg Q1 losses covered for Q1-Q2') ax2.bar([0], [0], color=[q_colors[1]], alpha=0.7, label='80% of avg Q1 losses covered for Q1-Q5') try: ax2.bar([5 * myQ + ii for ii in range(0, 4)], [dw, pds3_dw, pds3_dw, pds_dw], color=[q_colors[0], q_colors[1], q_colors[2], q_colors[3]], alpha=0.7) np.savetxt( '/Users/brian/Desktop/BANK/hh_resilience_model/output_plots/PH/pds_comparison_' + aProv + '_' + aDis + '_' + str(anRP) + '_Q' + str(myQ) + '.csv', [dw, pds_dw, pds2_dw], delimiter=',') except: pass out_str = None if myCountry == 'FJ': out_str = [ 'Asset loss', 'Consumption\nloss (NPV)', 'Wellbeing loss', 'Net cost of\nWinston-like\nsupport', 'Wellbeing loss\npost support' ] else: out_str = [ 'Asset loss', 'Wellbeing loss', 'Net cash benefit of\n' + pds_dict[my_PDS], 'Wellbeing loss\nwith ' + pds_dict[my_PDS] ] trans = ax.get_xaxis_transform() # x in data untis, y in axes fraction for ni, ii in enumerate(range(1, 5)): ann = ax.annotate(out_str[ni], xy=(6 * ii + 0.5, +0.005), xycoords=trans, ha='left', va='top', fontsize=8, annotation_clip=False) #ax.annotate(out_str[ni],xy=(6*ii+0.5,ax.get_ylim()[0]),xycoords='data',ha='left',va='top',weight='bold',fontsize=9,annotation_clip=False) fig = ax.get_figure() leg = ax.legend(loc='best', labelspacing=0.75, ncol=1, fontsize=8, borderpad=0.75, fancybox=True, frameon=True, framealpha=0.9) leg.get_frame().set_color('white') leg.get_frame().set_edgecolor(greys_pal[7]) leg.get_frame().set_linewidth(0.2) plt.figure(1) myxlim = ax.get_xlim() plt.plot([xlim for xlim in myxlim], [0, 0], 'k-', lw=0.75, color=greys_pal[3], zorder=100, alpha=0.85) plt.xlim(myxlim) ax.xaxis.set_ticks([]) ax.tick_params(axis='y', labelsize=8) #plt.plot(ax.get_xlim(),[0,0],color=greys_pal[2],linewidth=0.5,zorder=10) if currency != 'USD': currency = get_currency(myCountry)[0][-3:] plt.ylabel('Disaster losses (' + _curr_sf_str + currency.replace('USD', 'US$') + ' per affected person)', labelpad=10, fontsize=10) sns.despine(bottom=True) plt.grid(False) _success = False while not _success: try: fig.savefig(output_plots + 'npr_' + aProv.replace(' ', '') + '_' + aDis + '_' + str(anRP) + '_' + my_PDS + '_' + currency.lower() + '.pdf', format='pdf', bbox_inches='tight') #fig.savefig(output_plots+'png/npr_'+aProv.replace(' ','')+'_'+aDis+'_'+str(anRP)+'_'+my_PDS+'_'+currency.lower()+'.png',format='png',bbox_inches='tight') _success = True except: print('having trouble...') plt.figure(2) fig2 = ax2.get_figure() leg = ax2.legend(loc='best', labelspacing=0.75, ncol=1, fontsize=9, borderpad=0.75, fancybox=True, frameon=True, framealpha=0.9) leg.get_frame().set_color('white') leg.get_frame().set_edgecolor(greys_pal[7]) leg.get_frame().set_linewidth(0.2) ann_y = -ax2.get_ylim()[1] / 30 n_pds_options = 4 out_str = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5'] for ni, ii in enumerate(range(1, 6)): # quintiles ax2.annotate(out_str[ni], xy=(5 * ii + 0.05, ann_y), zorder=100, xycoords='data', ha='left', va='center', weight='bold', fontsize=9, annotation_clip=False) plt.plot([5 * ii + 1.20, 5 * ii + 3.78], [ann_y, ann_y], 'k-', lw=1.50, color=greys_pal[7], zorder=100, alpha=0.85) plt.plot([5 * ii + 3.78, 5 * ii + 3.78], [ann_y * 0.9, ann_y * 1.1], 'k-', lw=1.50, color=greys_pal[7], zorder=100, alpha=0.85) ax2.xaxis.set_ticks([]) plt.xlim(3, 32) plt.plot([i for i in ax2.get_xlim()], [0, 0], 'k-', lw=1.5, color=greys_pal[7], zorder=100, alpha=0.85) if currency != 'USD': currency = get_currency(myCountry)[0][-3:] plt.ylabel('Wellbeing losses (' + currency.replace('USD', 'US$') + ' per capita)', labelpad=10, fontsize=10) _success = False try: fig2.savefig(output_plots + 'npr_pds_schemes_' + aProv + '_' + aDis + '_' + str(anRP) + '_' + currency.lower() + '.pdf', format='pdf', bbox_inches='tight') #fig2.savefig(output_plots+'png/npr_pds_schemes_'+aProv+'_'+aDis+'_'+str(anRP)+'.png',format='png',bbox_inches='tight') _success = True except: print('not working..NOT trying again on npr_pds_schemes_***') plt.clf() plt.close('all')