def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['obs_infile','obs_varname','obs_units'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames, check_against='obs_infile') mand_argnames = ['ens_infile','ens_varname','ens_units','ens_color','ens_label','ens_pctlerange','ens_linestyle'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames, check_against='ens_infile') # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) # Get attributes for plotting conf_range = plot_dict['conf_range'] alpha = plot_dict['alpha'][0] ensure_taxis_same = plot_dict['ensure_taxis_same'][0] # Calculate quantiles for observations obs_infiles = pio.read_infile_list(plot_dict['obs_infile']) obs_varname = plot_dict['obs_varname'][0] obs_units = pio.fix_label(plot_dict['obs_units'][0]) pio.print_plotting_status(0,obs_varname,obs_units) obs_tseries = nio.concat_nctseries2array(obs_infiles,obs_varname,obs_units,ensure_taxis_same=ensure_taxis_same) obs_quantiles = calc_quantiles(obs_tseries) # Calculate quantiles for model ensemble(s) for i in range(len(plot_dict['ens_infile'])): ens_infiles = pio.read_infile_list(plot_dict['ens_infile'][i]) ens_varname = plot_dict['ens_varname'][i][0] ens_units = pio.fix_label(plot_dict['ens_units'][i][0]) ens_color = pio.fix_label(plot_dict['ens_color'][i][0]) ens_label = plot_dict['ens_label'][i][0] ens_pctlerange = plot_dict['ens_pctlerange'][i][0] ens_linestyle = pio.line_alias2style(plot_dict['ens_linestyle'][i][0]) mark_ptiles = plot_dict['mark_ptiles'] tickmark_size = plot_dict['tickmark_size'][0] pio.print_plotting_status(i+1,ens_varname, ens_units) ens_tseries = nio.concat_nctseries2array(ens_infiles,ens_varname,ens_units,ensure_taxis_same=ensure_taxis_same) ens_quantiles = calc_quantiles(ens_tseries) ax.plot(obs_quantiles, ens_quantiles, ens_linestyle, color=ens_color, label=ens_label,lw=1.5, zorder=3) if ens_pctlerange: n_qtles = len(obs_quantiles) n_ensmembers = ens_tseries.shape[0] store = np.zeros((n_ensmembers,n_qtles),'f') store[:] = np.nan for i in range(0,n_ensmembers): store[i,:] = calc_quantiles(ens_tseries[i,:]) conf_range_lower = np.zeros(n_qtles, 'f') conf_range_upper = np.zeros(n_qtles, 'f') conf_range_lower[:] = np.nan conf_range_upper[:] = np.nan for qtle in range(0,n_qtles): conf_range_lower[qtle] = stats.scoreatpercentile(store[:,qtle], conf_range[0]*100) conf_range_upper[qtle] = stats.scoreatpercentile(store[:,qtle], conf_range[1]*100) ax.fill_between(obs_quantiles, conf_range_lower, conf_range_upper, facecolor = ens_color, edgecolor = ens_color, alpha = alpha) if mark_ptiles: ens_range = ens_quantiles[-1] - ens_quantiles[0] for p in mark_ptiles: obs_p = stats.scoreatpercentile(obs_tseries.flatten(), p) ens_p = stats.scoreatpercentile(ens_tseries.flatten(), p) ax.plot(obs_p, ens_p,'ko', ms=5, zorder=1) ax.text(obs_p+0.03*ens_range, ens_p-0.04*ens_range, str(p), ha='center', va='bottom',zorder=1,fontsize=tickmark_size) # Add figure display options lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xylim = plot_dict['xylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] xy_mnrticks = plot_dict['xy_mnrticks'] ofile = plot_dict['ofile'][0] pio.plot_legend_no_repeats(ax, font_size = lgnd_size, loc = lgnd_loc) plt.tick_params(labelsize=tickmark_size) if xylim: assert xylim[0] < xylim[1] ax.set_xlim([xylim[0], xylim[1]]) ax.set_ylim([xylim[0], xylim[1]]) ax.plot(xylim,xylim,'k-') else: xlim = ax.get_xlim() ylim = ax.get_ylim() xylim = ( min(xlim[0],ylim[0]), max(xlim[1],ylim[1]) ) ax.set_xlim(xylim[0],xylim[1]) ax.set_xlim(xylim[0],xylim[1]) ax.plot(xylim,xylim,'k-') if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if xy_mnrticks: pio.set_yaxis_minorticks(ax,xy_mnrticks) pio.set_xaxis_minorticks(ax,xy_mnrticks) # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['varname','units','color','lgnd_label'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames) alpha = plot_dict['alpha'][0] grid = plot_dict['grid'][0] lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xlim = plot_dict['xlim'] ylim = plot_dict['ylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] whisker = plot_dict['whisker'][0] outliers = plot_dict['outliers'][0] ofile = plot_dict['ofile'][0] widths = plot_dict['box_width'][0] show_mean = (plot_dict['show_mean'][0] == 'True') xtick_rotation = plot_dict['xtick_rotation'][0] whis_override = False if whisker == '1.5': whis=1.5 print "whiskers are 1.5* interquartile range" elif whisker == 'range': whis='range' print "whiskers span min and max values" elif whisker == '5-95': whis=0 outliers='off' pctle=[5,95] whis_override = True print "whiskers span 5th to 95th percentiles" elif whisker == '10-90': whis=0 outliers='off' pctle=[10,90] whis_override = True print "whiskers span 10th to 90th percentiles" # read each set of infiles box_data=[] box_color=[] box_label=[] pctle_low=[] pctle_high=[] pctle_25=[] pctle_75=[] for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) color = pio.fix_label(plot_dict['color'][i][0]) label = pio.fix_label(plot_dict['lgnd_label'][i][0]) pio.print_plotting_status(i,varname, units) var_tseries = nio.concat_nctseries2array(infiles,varname,units,ensure_taxis_same='False') if whis_override == True : pctle_low.append( np.percentile(var_tseries,pctle[0]) ) pctle_high.append( np.percentile(var_tseries,pctle[1]) ) pctle_25.append( np.percentile(var_tseries,25) ) pctle_75.append( np.percentile(var_tseries,75) ) var_tseries = var_tseries.flatten() box_data.append(var_tseries) box_color.append(color) box_label.append(label) # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) if grid == 'on': ax.yaxis.grid(True) ax.set_axisbelow(True) if outliers == 'on': showfliers=True print "Box plot showing outliers" else: showfliers=False print "Box plot with outliers hidden" box = plt.boxplot(box_data, patch_artist=True, showmeans=show_mean, whis=whis, showfliers=showfliers, widths=widths) # add additional args here, such as whis options for patch, color in zip(box['boxes'], box_color): patch.set_facecolor(color) patch.set_alpha(alpha) if whis_override == True: wdth = 1./3. * widths plt.setp(box['caps'],linewidth=0.0) plt.setp(box['medians'], linewidth=2.5, color='black') plt.scatter(range(1,len(pctle_low)+1),pctle_low,marker='_') plt.scatter(range(1,len(pctle_high)+1),pctle_high,marker='_') plt.vlines(range(1,len(pctle_low)+1),pctle_low,pctle_25) plt.vlines(range(1,len(pctle_high)+1),pctle_high,pctle_75) plt.hlines(pctle_low,np.array(range(1,len(pctle_low)+1))-wdth,np.array(range(1,len(pctle_low)+1))+wdth) plt.hlines(pctle_high,np.array(range(1,len(pctle_high)+1))-wdth,np.array(range(1,len(pctle_high)+1))+wdth) plt.setp(ax, xticks=[y+1 for y in range(len(box_data))], xticklabels=box_label) labels = ax.get_xticklabels() plt.setp(labels, rotation=xtick_rotation) plt.tight_layout() if xlim: assert xlim[0] < xlim[1] ax.set_xlim([xlim[0], xlim[1]]) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax,y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax,x_mnrticks) # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['infile','varname','units','plot_type','color','lgnd_label'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames, check_against='infile') pio.check_inargs_opt_rpt(plot_dict,'line_style', default = 'solid') pio.check_inargs_opt_rpt(plot_dict,'line_width', default = 1.5) pio.check_inargs_opt_rpt(plot_dict,'marker_type', default = 'o') pio.check_inargs_opt_rpt(plot_dict,'marker_size', default = 1.5) pio.check_inargs_opt_rpt(plot_dict,'yaxis', default = 'primary') # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) ax2 = None if ['secondary'] in plot_dict['yaxis']: ax2 = ax.twinx() datasets=[] # Plot each tseries for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) line_style = pio.line_alias2style(plot_dict['line_style'][i][0]) line_color = pio.fix_label(plot_dict['color'][i][0]) line_width = plot_dict['line_width'][i][0] line_label = plot_dict['lgnd_label'][i][0] plot_type = plot_dict['plot_type'][i][0] yaxis = plot_dict['yaxis'][i][0] marker_size= plot_dict['marker_size'][i][0] ensure_taxis_same = plot_dict['ensure_taxis_same'][0] plot_anomaly = plot_dict['plt_anomaly'][0] show_bias = plot_dict['show_bias'][0] show_corr = plot_dict['show_corr'][0] if yaxis == 'primary': axn = ax else: axn = ax2 pio.print_plotting_status(i,varname, units) var_tseries,xdates = nio.concat_nctseries2array(infiles,varname,units,return_dates=True,ensure_taxis_same=ensure_taxis_same) datasets.append(var_tseries) if plot_anomaly == 'True': var_tseries = var_tseries - np.nanmean(var_tseries) if (len(var_tseries[0]) == 1) and (plot_type == 'tseries_conf'): raise ValueError, 'cannot plot confidence bounds for single timeseries' if (plot_type in ['tseries_line','tseries_marker']): if (plot_type == 'tseries_line'): fmt = line_style else: fmt = plot_dict['marker_type'][i][0] for mbr in range(0,var_tseries.shape[0]): axn.plot_date(xdates,var_tseries[mbr,:],fmt=fmt,color=line_color,linewidth=line_width,label=line_label, markersize = marker_size) elif (plot_type in ['tseries_conf_mean','tseries_conf_median']): if plot_type == 'tseries_conf_mean': thick = np.ma.mean(var_tseries, axis=0) elif plot_type == 'tseries_conf_median': thick = np.ma.median(var_tseries, axis=0) pctl_lwr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][0], axis=0) pctl_upr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][1], axis=0) axn.plot_date(xdates,thick,fmt=line_style,color=line_color,linewidth=line_width,label=line_label) axn.fill_between(xdates,pctl_lwr,pctl_upr,facecolor=line_color, alpha=plot_dict['alpha'][0], edgecolor=line_color) # Add figure display options if show_bias == 'True': bias = np.ma.mean(datasets[0]) - np.ma.mean(datasets[1]) lbl_bias = 'Bias: '+str(round(bias,2)) ax.text(0.05, 0.05, lbl_bias, transform=ax.transAxes, fontsize='large') if show_corr == 'True': r, p = stats.pearsonr(calc_ens_tmean(datasets[0]),calc_ens_tmean(datasets[1])) lbl_corr = 'r: '+str(round(r,2))+' (p '+str(round(p,2))+')' ax.text(0.70, 0.05, lbl_corr, transform=ax.transAxes, fontsize='large') if plot_dict['lgnd_loc']: markerscale = 6. / marker_size pio.plot_legend_no_repeats(ax, ax2, font_size = plot_dict['lgnd_size'][0], loc = plot_dict['lgnd_loc'][0], markerscale=markerscale) if plot_dict['xlim']: xmin = nio.get_datetime([plot_dict['xlim'][0],])[0] xmax = nio.get_datetime([plot_dict['xlim'][1],])[0] assert xmax > xmin ax.set_xlim([xmin, xmax]) if plot_dict['yplim']: ax.set_ylim([plot_dict['yplim'][0], plot_dict['yplim'][1]]) if plot_dict['yslim'] and ax2: ax2.set_ylim([plot_dict['yslim'][0], plot_dict['yslim'][1]]) if plot_dict['xlabel']: ax.set_xlabel(pio.fix_label(plot_dict['xlabel'][0])) if plot_dict['yplabel']: ax.set_ylabel(pio.fix_label(plot_dict['yplabel'][0])) if plot_dict['yslabel'] and ax2: ax2.set_ylabel(pio.fix_label(plot_dict['yslabel'][0])) if plot_dict['title']: ax.set_title(pio.fix_label(plot_dict['title'][0])) if plot_dict['yp_mnrticks']: pio.set_yaxis_minorticks(ax,plot_dict['yp_mnrticks'][0]) if plot_dict['ys_mnrticks'] and ax2: pio.set_yaxis_minorticks(ax2,plot_dict['ys_mnrticks'][0]) if plot_dict['x_mnrticks']: pio.set_xaxis_minorticks(ax,plot_dict['x_mnrticks'][0]) if plot_dict['date_format'][0]: ax.xaxis.set_major_formatter(DateFormatter(pio.fix_label(plot_dict['date_format'][0]))) # Save figure to file fig.savefig(plot_dict['ofile'][0])
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = [ 'infile', 'varname', 'units', 'plot_type', 'color', 'lgnd_label' ] pio.check_inargs_mand_rpt(plot_dict, args2check=mand_argnames, check_against='infile') pio.check_inargs_opt_rpt(plot_dict, 'line_style', default='solid') pio.check_inargs_opt_rpt(plot_dict, 'line_width', default=1.5) pio.check_inargs_opt_rpt(plot_dict, 'marker_type', default='o') pio.check_inargs_opt_rpt(plot_dict, 'marker_size', default=1.5) pio.check_inargs_opt_rpt(plot_dict, 'yaxis', default='primary') # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) ax2 = None if ['secondary'] in plot_dict['yaxis']: ax2 = ax.twinx() datasets = [] # Plot each tseries for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) line_style = pio.line_alias2style(plot_dict['line_style'][i][0]) line_color = pio.fix_label(plot_dict['color'][i][0]) line_width = plot_dict['line_width'][i][0] line_label = plot_dict['lgnd_label'][i][0] plot_type = plot_dict['plot_type'][i][0] yaxis = plot_dict['yaxis'][i][0] marker_size = plot_dict['marker_size'][i][0] ensure_taxis_same = plot_dict['ensure_taxis_same'][0] plot_anomaly = plot_dict['plt_anomaly'][0] show_bias = plot_dict['show_bias'][0] show_corr = plot_dict['show_corr'][0] if yaxis == 'primary': axn = ax else: axn = ax2 pio.print_plotting_status(i, varname, units) var_tseries, xdates = nio.concat_nctseries2array( infiles, varname, units, return_dates=True, ensure_taxis_same=ensure_taxis_same) datasets.append(var_tseries) if plot_anomaly == 'True': var_tseries = var_tseries - np.nanmean(var_tseries) if (len(var_tseries[0]) == 1) and (plot_type == 'tseries_conf'): raise ValueError, 'cannot plot confidence bounds for single timeseries' if (plot_type in ['tseries_line', 'tseries_marker']): if (plot_type == 'tseries_line'): fmt = line_style else: fmt = plot_dict['marker_type'][i][0] for mbr in range(0, var_tseries.shape[0]): axn.plot_date(xdates, var_tseries[mbr, :], fmt=fmt, color=line_color, linewidth=line_width, label=line_label, markersize=marker_size) elif (plot_type in ['tseries_conf_mean', 'tseries_conf_median']): if plot_type == 'tseries_conf_mean': thick = np.ma.mean(var_tseries, axis=0) elif plot_type == 'tseries_conf_median': thick = np.ma.median(var_tseries, axis=0) pctl_lwr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][0], axis=0) pctl_upr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][1], axis=0) axn.plot_date(xdates, thick, fmt=line_style, color=line_color, linewidth=line_width, label=line_label) axn.fill_between(xdates, pctl_lwr, pctl_upr, facecolor=line_color, alpha=plot_dict['alpha'][0], edgecolor=line_color) # Add figure display options if show_bias == 'True': bias = np.ma.mean(datasets[0]) - np.ma.mean(datasets[1]) lbl_bias = 'Bias: ' + str(round(bias, 2)) ax.text(0.05, 0.05, lbl_bias, transform=ax.transAxes, fontsize='large') if show_corr == 'True': r, p = stats.pearsonr(calc_ens_tmean(datasets[0]), calc_ens_tmean(datasets[1])) lbl_corr = 'r: ' + str(round(r, 2)) + ' (p ' + str(round(p, 2)) + ')' ax.text(0.70, 0.05, lbl_corr, transform=ax.transAxes, fontsize='large') if plot_dict['lgnd_loc']: markerscale = 6. / marker_size pio.plot_legend_no_repeats(ax, ax2, font_size=plot_dict['lgnd_size'][0], loc=plot_dict['lgnd_loc'][0], markerscale=markerscale) if plot_dict['xlim']: xmin = nio.get_datetime([ plot_dict['xlim'][0], ])[0] xmax = nio.get_datetime([ plot_dict['xlim'][1], ])[0] assert xmax > xmin ax.set_xlim([xmin, xmax]) if plot_dict['yplim']: ax.set_ylim([plot_dict['yplim'][0], plot_dict['yplim'][1]]) if plot_dict['yslim'] and ax2: ax2.set_ylim([plot_dict['yslim'][0], plot_dict['yslim'][1]]) if plot_dict['xlabel']: ax.set_xlabel(pio.fix_label(plot_dict['xlabel'][0])) if plot_dict['yplabel']: ax.set_ylabel(pio.fix_label(plot_dict['yplabel'][0])) if plot_dict['yslabel'] and ax2: ax2.set_ylabel(pio.fix_label(plot_dict['yslabel'][0])) if plot_dict['title']: ax.set_title(pio.fix_label(plot_dict['title'][0])) if plot_dict['yp_mnrticks']: pio.set_yaxis_minorticks(ax, plot_dict['yp_mnrticks'][0]) if plot_dict['ys_mnrticks'] and ax2: pio.set_yaxis_minorticks(ax2, plot_dict['ys_mnrticks'][0]) if plot_dict['x_mnrticks']: pio.set_xaxis_minorticks(ax, plot_dict['x_mnrticks'][0]) if plot_dict['date_format'][0]: ax.xaxis.set_major_formatter( DateFormatter(pio.fix_label(plot_dict['date_format'][0]))) # Save figure to file fig.savefig(plot_dict['ofile'][0])
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['varname', 'units', 'color', 'lgnd_label', 'plot_kde'] pio.check_inargs_mand_rpt(plot_dict, args2check=mand_argnames) # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) # Get attributes for plotting alpha = plot_dict['alpha'][0] binwidth = plot_dict['binwidth'][0] label_mean = plot_dict['label_mean'][0] bins = np.arange(-10000, 10000, binwidth) x_min = 0 x_max = 0 delta = 0 # Plot each tseries for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) color = pio.fix_label(plot_dict['color'][i][0]) label = plot_dict['lgnd_label'][i][0] plot_kde = plot_dict['plot_kde'][i][0] pio.print_plotting_status(i, varname, units) var_tseries = nio.concat_nctseries2array(infiles, varname, units, check_axis='False', ensure_taxis_same='False') var_tseries = var_tseries.flatten() var_tseries = var_tseries[~np.isnan(var_tseries)] if plot_kde == 'True': kde = gaussian_kde(var_tseries) xvals = np.linspace(np.min(var_tseries), np.max(var_tseries), 100) ax.plot(xvals, kde(xvals), color=color, alpha=alpha, label=label) else: ax.hist(var_tseries, bins=bins, normed=1, histtype='stepfilled', facecolor=color, alpha=alpha, label=label) if np.nanmin(var_tseries) < x_min: x_min = np.nanmin(var_tseries) if np.nanmax(var_tseries) > x_max: x_max = np.nanmax(var_tseries) if label_mean == 'True': label = pio.fix_label(label) var_mean = np.nanmean(var_tseries) var_std = np.nanstd(var_tseries) lbl_mean = 'Mean ' + label + ': ' + str(round(var_mean, 2)) lbl_std = 'StDev ' + label + ': ' + str(round(var_std, 2)) ax.text(0.05, (0.95 - delta), lbl_mean, transform=ax.transAxes, fontsize='small') ax.text(0.05, (0.90 - delta), lbl_std, transform=ax.transAxes, fontsize='small') delta = delta + 0.10 # Add figure display options plot_threshold = plot_dict['plot_threshold'][0] lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xlim = plot_dict['xlim'] ylim = plot_dict['ylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] ofile = plot_dict['ofile'][0] pio.plot_legend_no_repeats(ax, font_size=lgnd_size, loc=lgnd_loc) # set xlim using default min/max ax.set_xlim([x_min, x_max]) if xlim: assert xlim[0] < xlim[1] ax.set_xlim([xlim[0], xlim[1]]) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax, y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax, x_mnrticks) if plot_threshold: ax.plot([plot_threshold, plot_threshold], [ax.get_ylim()[0], ax.get_ylim()[1]], '--', color='black') # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['varname','units','color','lgnd_label','plot_kde'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames) # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) # Get attributes for plotting alpha = plot_dict['alpha'][0] binwidth = plot_dict['binwidth'][0] label_mean = plot_dict['label_mean'][0] bins=np.arange(-10000, 10000 , binwidth) x_min=0 x_max=0 delta=0 # Plot each tseries for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) color = pio.fix_label(plot_dict['color'][i][0]) label = plot_dict['lgnd_label'][i][0] plot_kde = plot_dict['plot_kde'][i][0] pio.print_plotting_status(i,varname, units) var_tseries = nio.concat_nctseries2array(infiles,varname,units,check_axis='False',ensure_taxis_same='False') var_tseries = var_tseries.flatten() var_tseries = var_tseries[~np.isnan(var_tseries)] if plot_kde == 'True': kde = gaussian_kde(var_tseries) xvals = np.linspace(np.min(var_tseries), np.max(var_tseries), 100) ax.plot(xvals,kde(xvals), color=color, alpha=alpha, label=label) else: ax.hist(var_tseries, bins=bins, normed=1, histtype='stepfilled', facecolor=color, alpha=alpha, label=label) if np.nanmin(var_tseries) < x_min : x_min = np.nanmin(var_tseries) if np.nanmax(var_tseries) > x_max : x_max = np.nanmax(var_tseries) if label_mean == 'True': label = pio.fix_label(label) var_mean = np.nanmean(var_tseries) var_std = np.nanstd(var_tseries) lbl_mean = 'Mean '+label+': '+str(round(var_mean,2)) lbl_std = 'StDev '+label+': '+str(round(var_std,2)) ax.text(0.05, (0.95 - delta), lbl_mean, transform=ax.transAxes, fontsize='small') ax.text(0.05, (0.90 - delta), lbl_std, transform=ax.transAxes, fontsize='small') delta = delta + 0.10 # Add figure display options plot_threshold = plot_dict['plot_threshold'][0] lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xlim = plot_dict['xlim'] ylim = plot_dict['ylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] ofile = plot_dict['ofile'][0] pio.plot_legend_no_repeats(ax, font_size = lgnd_size, loc = lgnd_loc) # set xlim using default min/max ax.set_xlim([x_min, x_max]) if xlim: assert xlim[0] < xlim[1] ax.set_xlim([xlim[0], xlim[1]]) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax,y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax,x_mnrticks) if plot_threshold: ax.plot([plot_threshold,plot_threshold], [ax.get_ylim()[0],ax.get_ylim()[1]],'--', color='black') # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = [ 'infile', 'varname', 'units', 'plot_conf', 'color', 'lgnd_label', 'period' ] pio.check_inargs_mand_rpt(plot_dict, args2check=mand_argnames, check_against='infile') # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) # Get attributes for plotting conf_range = plot_dict['conf_range'] marker_size = plot_dict['marker_size'][0] direction = plot_dict['direction'][0] bsn = plot_dict['bsn'][0] highlight_val = plot_dict['highlight_val'] alpha = plot_dict['alpha'][0] zoom = False if plot_dict['zoom_fctr']: for i in ['zoom_fctr', 'zoom_xlim', 'zoom_ylim']: if not plot_dict[i]: raise ValueError, 'need to specify argument --' + i zoom = True zoom_fctr = plot_dict['zoom_fctr'][0] zoom_loc = plot_dict['zoom_loc'][0] zoom_xlim = plot_dict['zoom_xlim'] zoom_ylim = plot_dict['zoom_ylim'] zoom_cnrs = plot_dict['zoom_line_cnrs'] zoom_xyticklbs = plot_dict['zoom_xyticklbs'][0] assert zoom_xlim[0] < zoom_xlim[1] assert zoom_ylim[0] < zoom_ylim[1] axins = zoomed_inset_axes(ax, zoom=zoom_fctr, loc=zoom_loc, borderpad=1.5) # Plot each tseries for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) plot_conf = plot_dict['plot_conf'][i][0] color = pio.fix_label(plot_dict['color'][i][0]) label = plot_dict['lgnd_label'][i][0] period = plot_dict['period'][i][0] pio.print_plotting_status(i, varname, units) var_tseries = nio.concat_nctseries2array(infiles, varname, units, ensure_taxis_same='False') xvals, yvals = pio.calc_return_times(var_tseries, direction=direction, period=period) ax.semilogx(xvals, yvals, 'ko', color=color, marker='o', markersize=marker_size, markeredgecolor=color, label=label) if zoom: axins.semilogx(xvals, yvals, 'ko', color=color, marker='o', markersize=marker_size, markeredgecolor=color, label=label) if highlight_val: highlight(ax, xvals, yvals, highlight_val, direction, marker_size) if zoom: highlight(axins, xvals, yvals, highlight_val, direction, marker_size) if plot_conf == 'True': conf_vals = pio.calc_return_time_confidences( var_tseries, direction=direction, c=[conf_range[0], conf_range[1]], bsn=bsn) ax.fill_between(xvals, conf_vals[0], conf_vals[1], facecolor=color, alpha=alpha, edgecolor=color) if zoom: axins.fill_between(xvals, conf_vals[0], conf_vals[1], facecolor=color, alpha=alpha, edgecolor=color) # Add figure display options lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xlim = plot_dict['xlim'] ylim = plot_dict['ylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] ofile = plot_dict['ofile'][0] markerscale = 6. / marker_size pio.plot_legend_no_repeats(ax, font_size=lgnd_size, loc=lgnd_loc, markerscale=markerscale) if xlim: assert xlim[0] < xlim[1] ax.set_xlim([xlim[0], xlim[1]]) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax, y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax, x_mnrticks) if zoom: axins.set_xlim(zoom_xlim[0], zoom_xlim[1]) axins.set_ylim(zoom_ylim[0], zoom_ylim[1]) mark_inset(ax, axins, loc1=zoom_cnrs[0], loc2=zoom_cnrs[1], fc="none", ec="0.5") if zoom_xyticklbs == 'off': axins.set_xticklabels([]) axins.set_yticklabels([]) # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['varname','units','color','xlabel'] pio.check_inargs_mand_rpt(plot_dict, args2check = mand_argnames) # Initialise figure alpha = plot_dict['alpha'][0] grid = plot_dict['grid'][0] ylim = plot_dict['ylim'] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] ofile = plot_dict['ofile'][0] fig = plt.figure() ax = fig.add_subplot(111) labels = [] xvals = [] for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) color = pio.fix_label(plot_dict['color'][i][0]) label = pio.fix_label(plot_dict['xlabel'][i][0]) plot_type = plot_dict['plot_type'][0] pio.print_plotting_status(i,varname, units) var_tseries = nio.concat_nctseries2array(infiles,varname,units,ensure_taxis_same='False') var_tseries = var_tseries.flatten() mean = gio.calc_nanmean(var_tseries, axis=0) pctl_lwr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][0], axis=0) pctl_upr = gio.calc_nanquantile(var_tseries, q=plot_dict['conf_range'][1], axis=0) labels.append(label) xvals.append(i) if plot_type == 'errbar': ax.plot(i,mean,marker='o',markersize=plot_dict['marker_size'][0],markerfacecolor=color,markeredgecolor=color) ax.plot([i,i],[pctl_lwr,pctl_upr],c=color,linewidth=plot_dict['line_width'][0]) elif plot_type == 'points': var_tseries.flatten() for n in xrange(0,len(var_tseries)): ax.plot(i,var_tseries[n],marker='o',markersize=plot_dict['marker_size'][0],markerfacecolor=color,markeredgecolor=color) plt.xticks(xvals,labels,rotation=plot_dict['xlabel_rotation'][0]) ax.tick_params(axis='x', labelsize=plot_dict['xlabel_size'][0]) ax.set_xlim(-1,len(plot_dict['infile'])) plt.subplots_adjust(bottom=0.15) if grid == 'on': ax.yaxis.grid(True) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax,y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax,x_mnrticks) # Save figure to file fig.savefig(ofile)
def main(inargs): # Check input arguments plot_dict = vars(inargs) del inargs mand_argnames = ['varname', 'units', 'color', 'lgnd_label'] pio.check_inargs_mand_rpt(plot_dict, args2check=mand_argnames) alpha = plot_dict['alpha'][0] grid = plot_dict['grid'][0] lgnd_size = plot_dict['lgnd_size'][0] lgnd_loc = plot_dict['lgnd_loc'][0] xlim = plot_dict['xlim'] ylim = plot_dict['ylim'] xlabel = plot_dict['xlabel'][0] ylabel = plot_dict['ylabel'][0] title = plot_dict['title'][0] y_mnrticks = plot_dict['y_mnrticks'] x_mnrticks = plot_dict['x_mnrticks'] whisker = plot_dict['whisker'][0] outliers = plot_dict['outliers'][0] ofile = plot_dict['ofile'][0] widths = plot_dict['box_width'][0] show_mean = (plot_dict['show_mean'][0] == 'True') xtick_rotation = plot_dict['xtick_rotation'][0] whis_override = False if whisker == '1.5': whis = 1.5 print "whiskers are 1.5* interquartile range" elif whisker == 'range': whis = 'range' print "whiskers span min and max values" elif whisker == '5-95': whis = 0 outliers = 'off' pctle = [5, 95] whis_override = True print "whiskers span 5th to 95th percentiles" elif whisker == '10-90': whis = 0 outliers = 'off' pctle = [10, 90] whis_override = True print "whiskers span 10th to 90th percentiles" # read each set of infiles box_data = [] box_color = [] box_label = [] pctle_low = [] pctle_high = [] pctle_25 = [] pctle_75 = [] for i in range(len(plot_dict['infile'])): infiles = pio.read_infile_list(plot_dict['infile'][i]) varname = plot_dict['varname'][i][0] units = pio.fix_label(plot_dict['units'][i][0]) color = pio.fix_label(plot_dict['color'][i][0]) label = pio.fix_label(plot_dict['lgnd_label'][i][0]) pio.print_plotting_status(i, varname, units) var_tseries = nio.concat_nctseries2array(infiles, varname, units, ensure_taxis_same='False') if whis_override == True: pctle_low.append(np.percentile(var_tseries, pctle[0])) pctle_high.append(np.percentile(var_tseries, pctle[1])) pctle_25.append(np.percentile(var_tseries, 25)) pctle_75.append(np.percentile(var_tseries, 75)) var_tseries = var_tseries.flatten() box_data.append(var_tseries) box_color.append(color) box_label.append(label) # Initialise figure fig = plt.figure() ax = fig.add_subplot(111) if grid == 'on': ax.yaxis.grid(True) ax.set_axisbelow(True) if outliers == 'on': showfliers = True print "Box plot showing outliers" else: showfliers = False print "Box plot with outliers hidden" box = plt.boxplot( box_data, patch_artist=True, showmeans=show_mean, whis=whis, showfliers=showfliers, widths=widths) # add additional args here, such as whis options for patch, color in zip(box['boxes'], box_color): patch.set_facecolor(color) patch.set_alpha(alpha) if whis_override == True: wdth = 1. / 3. * widths plt.setp(box['caps'], linewidth=0.0) plt.setp(box['medians'], linewidth=2.5, color='black') plt.scatter(range(1, len(pctle_low) + 1), pctle_low, marker='_') plt.scatter(range(1, len(pctle_high) + 1), pctle_high, marker='_') plt.vlines(range(1, len(pctle_low) + 1), pctle_low, pctle_25) plt.vlines(range(1, len(pctle_high) + 1), pctle_high, pctle_75) plt.hlines(pctle_low, np.array(range(1, len(pctle_low) + 1)) - wdth, np.array(range(1, len(pctle_low) + 1)) + wdth) plt.hlines(pctle_high, np.array(range(1, len(pctle_high) + 1)) - wdth, np.array(range(1, len(pctle_high) + 1)) + wdth) plt.setp(ax, xticks=[y + 1 for y in range(len(box_data))], xticklabels=box_label) labels = ax.get_xticklabels() plt.setp(labels, rotation=xtick_rotation) plt.tight_layout() if xlim: assert xlim[0] < xlim[1] ax.set_xlim([xlim[0], xlim[1]]) if ylim: assert ylim[0] < ylim[1] ax.set_ylim([ylim[0], ylim[1]]) if xlabel: ax.set_xlabel(pio.fix_label(xlabel)) if ylabel: ax.set_ylabel(pio.fix_label(ylabel)) if title: ax.set_title(pio.fix_label(title)) if y_mnrticks: pio.set_yaxis_minorticks(ax, y_mnrticks) if x_mnrticks: pio.set_xaxis_minorticks(ax, x_mnrticks) # Save figure to file fig.savefig(ofile)