def plot_map(test_data, ref_data, region, parameter): """Create figure, projection for maps""" test = test_data["{}_density".format(region)] test_num_years = test_data["{}_num_years".format(region)] ref = ref_data["{}_density".format(region)] ref_num_years = ref_data["{}_num_years".format(region)] fig = plt.figure(figsize=[8.5, 8.5], dpi=parameter.dpi) proj = ccrs.PlateCarree(central_longitude=180) # First panel plot_panel( 0, fig, proj, test, test_num_years, region, parameter.test_title, ) # Second panel plot_panel( 1, fig, proj, ref, ref_num_years, region, parameter.ref_title, ) # Figure title fig.suptitle(plot_info[region][3], x=0.5, y=0.9, fontsize=14) # plt.show() output_file_name = "{}-density-map".format(region) for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) print("Plot saved in: " + fnm) plt.close()
def plot(reference, test, diff, metrics_dict, parameter): # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) proj = ccrs.PlateCarree() # First two panels min1 = metrics_dict["test"]["min"] mean1 = metrics_dict["test"]["mean"] max1 = metrics_dict["test"]["max"] plot_panel( 0, fig, proj, test, parameter.contour_levels, parameter.test_colormap, (parameter.test_name_yrs, parameter.test_title, test.units), parameter, stats=(max1, mean1, min1), ) min2 = metrics_dict["ref"]["min"] mean2 = metrics_dict["ref"]["mean"] max2 = metrics_dict["ref"]["max"] plot_panel( 1, fig, proj, reference, parameter.contour_levels, parameter.reference_colormap, (parameter.ref_name_yrs, parameter.reference_title, reference.units), parameter, stats=(max2, mean2, min2), ) # Third panel min3 = metrics_dict["diff"]["min"] mean3 = metrics_dict["diff"]["mean"] max3 = metrics_dict["diff"]["max"] r = metrics_dict["misc"]["rmse"] c = metrics_dict["misc"]["corr"] plot_panel( 2, fig, proj, diff, parameter.diff_levels, parameter.diff_colormap, (None, parameter.diff_title, test.units), parameter, stats=(max3, mean3, min3, r, c), ) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.96, fontsize=18) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file + "." + f, ) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file + "." + f, ) print("Plot saved in: " + fnm) # Save individual subplots for f in parameter.output_format_subplot: fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file, ) page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot fname = fnm + ".%i." % (i) + f plt.savefig(fname, bbox_inches=extent) orig_fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file, ) fname = orig_fnm + ".%i." % (i) + f print("Sub-plot saved in: " + fname) i += 1 plt.close()
def plot_diurnal_cycle_zt(var, vars_to_data, parameter): ref = vars_to_data.refs[0] test = vars_to_data.test lst = vars_to_data.misc month = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ] for index in range(2): fig, axs = plt.subplots( 4, 3, figsize=(15, 12), facecolor="w", edgecolor="k", sharex=True, sharey=True, ) fig.subplots_adjust(hspace=0.4, wspace=0.1) axs = axs.ravel() t_conv = lst[0][0][0] for imon in range(12): if index == 0: title = parameter.ref_name data = ref data_name = "ref" if "armdiags" in title: data = data[:, :, ::-1] else: title = parameter.test_name data = test data_name = "test" time_freq = data.shape[1] yy = np.linspace(0, 48, time_freq * 2) xx = np.linspace(100, 1000, 37) x, y = np.meshgrid(xx, yy) data_con = np.concatenate((data[imon, :, :], data[imon, :, :]), axis=0) im = axs[imon].pcolormesh(y, x, data_con[:, :], vmin=0, vmax=30, cmap="jet", shading="auto") axs[imon].set_title(month[imon]) plt.xlim([24 - t_conv, 47 - t_conv]) xax = np.arange(24 - t_conv, 47 - t_conv, 3) my_xticks = ["0", "3", "6", "9", "12", "15", "18", "21"] plt.xticks(xax, my_xticks) axs[imon].xaxis.set_tick_params(labelbottom=True) # for ax in axs[9:12]: axs[imon].set_xlabel("Local time (hr)") for ax in axs[::3]: ax.set_ylabel("Pressure (mb)") axs[0].invert_yaxis() site = parameter.output_file.split("-")[-1] suptitle = "Cloud Fraction Monthly Diurnal Cycle " + site + "\n" + title plt.suptitle(suptitle, fontsize=20) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im, cax=cbar_ax) plt.title("cl (%)") output_file_name = parameter.output_file + "-" + data_name for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), output_file_name + "." + f, ) print("Plot saved in: " + fnm) plt.close()
def plot_diurnal_cycle(var, vars_to_data, parameter): test = vars_to_data.test[0] ref = vars_to_data.refs[0][0] lst = vars_to_data.misc[0] t_conv = lst[0][0] output_file_name = parameter.output_file + "-" + "diurnal-cycle" fig = plt.figure() # Create figure ax = fig.add_axes([0.15, 0.1, 0.8, 0.8]) # Create axes for index in range(2): if index == 0: data = test line_c = "k" data_name = parameter.test_name else: data = ref line_c = "r" data_name = parameter.ref_name time_freq = len(data) res = int(24 / time_freq) c, maxvalue, tmax = fastAllGridFT(data, [0]) xax = np.linspace(0, 48 - res, time_freq * 2) ax.plot(xax, np.concatenate((data, data)), "." + line_c, label=data_name) xax = np.linspace(0, 48 - res, time_freq * 2 * 3) w = 2.0 * np.pi / 24 yax = (c + maxvalue[0] * np.sin(w * xax + np.pi / 2 - tmax[0] * w))[0] ax.plot(xax, yax, line_c, label="First harmonic") plt.xlim([24 - t_conv, 47 - t_conv + 1]) plt.ylim([0, 5.5]) # ymin, ymax = plt.gca().get_ylim() # plt.ylim(ymin, ymax) plt.xlabel("local solar time [hr]") # plt.ylabel(parameter.var_name + ' (' +parameter.var_units+ ')') plt.ylabel("Total Precipitation Rate" + " (" + parameter.var_units + ")") xax = np.arange(24 - t_conv, 47 - t_conv, 3) my_xticks = ["0h", "3h", "6h", "9h", "12h", "15h", "18h", "21h"] plt.xticks(xax, my_xticks) plt.legend(loc="upper right") plt.title(output_file_name.replace("-", " ")) for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join(get_output_dir(parameter.current_set, parameter), output_file_name + "." + f) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), output_file_name + "." + f, ) print("Plot saved in: " + fnm) plt.close()
def plot_annual_cycle(var, vars_to_data, parameter): line_color = ["r", "b", "g", "m"] fig = plt.figure() # Create figure ax1 = fig.add_axes([0.15, 0.1, 0.8, 0.8]) # Create axes xax = np.arange(1, 13, 1) refs = vars_to_data.refs test = vars_to_data.test ax1.plot( xax, test.asma(), "k", linewidth=2, label="Test: " + parameter.test_name) # +' ({0:.1f})'.format(np.mean(test.asma()))) test_season = get_seasonal_mean(test) for i_ref, ref in enumerate(refs): ref_season = get_seasonal_mean(ref) ax1.plot( xax, ref.asma(), line_color[i_ref], linewidth=2, label="Ref: " + parameter.ref_name, ) # +' ({0:.1f})'.format(np.mean(ref.asma()))) my_xticks = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"] plt.xticks(xax, my_xticks) plt.xlim(1, 12) ymin, ymax = plt.gca().get_ylim() plt.ylim(0.8 * ymin, 1.2 * ymax) # plt.ylim(ylim[va_ind]) plt.xlabel("Month") plt.legend(loc="best", prop={"size": 10}) if var == "PRECT": plt.ylabel("Total Precipitation Rate" + " (" + parameter.var_units + ")") else: plt.ylabel(parameter.var_name + " (" + parameter.var_units + ")") # Add a table at the bottom of the axes bias = test_season - ref_season cell_text = np.round(np.vstack((test_season, ref_season, bias)), 2) collabel = ("ANN", "DJF", "MAM", "JJA", "SON") rows = ("Test", "Ref", "Bias") plt.table( cellText=cell_text, rowLabels=rows, colLabels=collabel, alpha=0.8, bbox=[0.15, 0.0, 0.8, 0.2], ) # Save the figure. output_file_name = parameter.output_file plt.title(output_file_name.replace("-", " ")) for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join(get_output_dir(parameter.current_set, parameter), output_file_name + "." + f) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), output_file_name + "." + f, ) print("Plot saved in: " + fnm) plt.close()
def plot_convection_onset_statistics(test_pr, test_prw, ref_pr, ref_prw, parameter, region): # Original code: Kathleen Schiro, python version 22 Dec 2016, University of California Dept. of Atmospheric and Oceanic Sciences # Modifications: Baird Langenbrunner, Yi-Hung Kuo # Modifications: Jill Zhang, Cheng Tao # Scientific supervision: Prof. J David Neelin # # For related publications and research information see # the Neelin group webpage http://www.atmos.ucla.edu/~csi/ # # Define precip threshold precip_threshold = 0.5 # default 0.5 (in mm/hr) # Define cwc bounds and bin_width for each site if region == "twpc1": # twpc1 cwv_max = 69 cwv_min = 28 bin_width = 1.5 sitename = "Manus Island" if region == "twpc2": # twpc2 cwv_max = 70 cwv_min = 28 bin_width = 2.0 sitename = "Nauru" if region == "twpc3": # twpc3 cwv_max = 85 cwv_min = 28 bin_width = 2.0 sitename = "Darwin" if region == "sgp": # sgp cwv_max = 75 cwv_min = 20 bin_width = 2.0 sitename = "SGP" fig, axes = plt.subplots(1, 3, figsize=(12, 3)) fig.subplots_adjust(wspace=0.3) title = "" for index in range(2): if index == 0: precip = test_pr cwv = test_prw data_name = "Test: " + parameter.test_name time_interval = 3 line_color = ["black", "grey"] else: precip = ref_pr cwv = ref_prw data_name = "Ref: " + parameter.ref_name time_interval = 1 line_color = ["blue", "steelblue"] var_time_absolute = cwv.getTime().asComponentTime() time_interval = int(var_time_absolute[1].hour - var_time_absolute[0].hour) number_of_bins = int(np.ceil((cwv_max - cwv_min) / bin_width)) bin_center = np.arange( (cwv_min + (bin_width / 2)), (cwv_max - (bin_width / 2)) + bin_width, bin_width, ) if len(bin_center) != number_of_bins: bin_center = np.arange((cwv_min + (bin_width / 2)), (cwv_max - (bin_width / 2)), bin_width) # Define variables for binning bin_index = np.zeros([number_of_bins, cwv.size]) precip_binned = np.empty([number_of_bins, cwv.size]) * np.nan precip_counts = np.zeros([number_of_bins, cwv.size]) np.warnings.filterwarnings("ignore") # Bin the data by CWV value as specified above for i in range(0, number_of_bins): tmp1 = np.where(cwv > cwv_min + (i * bin_width)) bin_index[i, tmp1] = 1 tmp2 = np.where(cwv > cwv_min + (i * bin_width) + bin_width) bin_index[i, tmp2] = 0 for i in range(0, number_of_bins): tmp1 = np.where(bin_index[i, :] == 1) precip_binned[i, tmp1] = precip[tmp1] tmp2 = np.where(bin_index[i, :] != 1) precip_binned[i, tmp2] = np.nan for i in range(0, number_of_bins): tmp1 = np.where(precip_binned[i, :] >= precip_threshold) precip_counts[i, tmp1] = 1 for j in range(0, cwv.size): if np.isnan(precip_binned[i, j]): precip_counts[i, j] = np.nan # Create binned arrays hist_cwv = np.empty([number_of_bins, 1]) * np.nan hist_precip_points = np.empty([number_of_bins, 1]) * np.nan pr_binned_mean = np.empty([number_of_bins, 1]) * np.nan pr_binned_std = np.empty([number_of_bins, 1]) * np.nan pr_probability = np.empty([number_of_bins, 1]) * np.nan errorbar_precip_points = np.empty([number_of_bins, 1]) * np.nan errorbar_precip = np.empty([number_of_bins, 1]) * np.nan ### errorbar_precip_binom = np.empty([number_of_bins, 2]) * np.nan # Fill binned arrays hist_cwv = bin_index.sum(axis=1) hist_cwv[hist_cwv <= 1] = 0 hist_precip_points = np.nansum(precip_counts, axis=1) hist_precip_points[hist_precip_points <= 1] = 0 pr_binned_mean = np.nanmean(precip_binned, axis=1) pr_binned_std = np.nanstd(precip_binned, axis=1) r = np.empty([1, number_of_bins]) * np.nan r = np.sum(~np.isnan(precip_counts), axis=1) pr_probability = np.nansum(precip_counts, axis=1) / r freq_cwv = (hist_cwv / bin_width) / np.nansum(hist_cwv) freq_precipitating_points = hist_precip_points / bin_width / np.nansum( hist_cwv) for i in range(0, number_of_bins): errorbar_precip[i] = pr_binned_std[i] / math.sqrt(hist_cwv[i]) errorbar_precip_points[i] = (math.sqrt(hist_precip_points[i]) / np.nansum(hist_cwv / bin_width) / bin_width) z = 0.675 phat = hist_precip_points[i] / hist_cwv[i] errorbar_precip_binom[i, 0] = z * math.sqrt(phat * (1 - phat) / hist_cwv[i]) errorbar_precip_binom[i, 1] = z * math.sqrt(phat * (1 - phat) / hist_cwv[i]) axes_fontsize = 12 # size of font in all plots legend_fontsize = 9 marker_size = 40 # size of markers in scatter plots xtick_pad = 10 # padding between x tick labels and actual plot bin_width = (np.max(bin_center) - np.min(bin_center)) / number_of_bins # create figure canvas # create figure 1 ax1 = axes[0] xulim = 5 * np.ceil(np.max(np.round(bin_center + bin_width / 2)) / 5) xllim = 5 * np.floor(np.min(np.round(bin_center - bin_width / 2)) / 5) # ax1.set_xlim(xllim-10,xulim+15) # ax1.set_xticks(np.arange(np.ceil(xllim/10)*10-10,np.ceil(xulim/10)*10+15,15)) # ax1.set_yticks(np.arange(0,5)) ax1.tick_params(labelsize=axes_fontsize) ax1.tick_params(axis="x", pad=10) ax1.errorbar( bin_center, pr_binned_mean, xerr=0, yerr=errorbar_precip.squeeze(), ls="none", color="black", ) # ax1.scatter(bin_center, pr_binned_mean, edgecolor='none', facecolor=scatter_colors, s=marker_size, clip_on=False, zorder=3) ax1.scatter( bin_center, pr_binned_mean, edgecolor="none", facecolor=line_color[0], s=marker_size, clip_on=True, zorder=3, label=data_name.split(":")[0], ) ax1.set_xlim(xllim - 10, cwv_max) ax1.set_ylim(0, 3) ax1.set_ylabel("Precip (mm/hr)", fontsize=axes_fontsize) ax1.set_xlabel("CWV (mm)", fontsize=axes_fontsize) ax1.set_axisbelow(True) legend_handles, legend_labels = ax1.get_legend_handles_labels() ax1.legend(legend_handles, legend_labels, loc="upper left", frameon=False) # create figure 2 (probability pickup) ax2 = axes[1] xulim = 5 * np.ceil(np.max(np.round(bin_center + bin_width / 2)) / 5) xllim = 5 * np.floor(np.min(np.round(bin_center - bin_width / 2)) / 5) # ax2.set_xlim(xllim-10,xulim+15) ax2.tick_params(labelsize=axes_fontsize) ax2.errorbar( bin_center, pr_probability, xerr=0, yerr=errorbar_precip_binom.T, fmt="none", color="black", ) ax2.tick_params(axis="x", pad=xtick_pad) ax2.scatter( bin_center, pr_probability, marker="d", s=marker_size, edgecolor="none", facecolor=line_color[0], zorder=3, label=data_name.split(":")[0], ) ax2.set_xlim(xllim - 10, cwv_max) # ax2.set_xticks(np.arange(np.ceil(xllim/10)*10-10,np.ceil(xulim/10)*10+15,15)) ax2.set_ylim(0, 1) ax2.set_yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) ax2.set_ylabel("Probability of Precip.", fontsize=axes_fontsize) ax2.set_xlabel("CWV (mm)", fontsize=axes_fontsize) # ax2.grid() ax2.set_axisbelow(True) legend_handles, legend_labels = ax2.get_legend_handles_labels() ax2.legend(legend_handles, legend_labels, loc="upper left", frameon=False) title = (title + data_name + ": " + str(time_interval) + " hrly(" + line_color[0] + ")\n") # create figure 3 (non-normalized PDF) ax3 = axes[2] ax3.set_yscale("log") xulim = 5 * np.ceil(np.max(np.round(bin_center + bin_width / 2)) / 5) xllim = 5 * np.floor(np.min(np.round(bin_center - bin_width / 2)) / 5) # ax3.set_xlim(xllim-10,xulim+15) ax3.set_xlim(xllim - 10, cwv_max) ax3.set_xticks( np.arange( np.ceil(xllim / 10) * 10 - 10, np.ceil(xulim / 10) * 10 + 15, 15)) # low_lim = -6.0 low_lim = -4.0 ax3.set_ylim(10**low_lim, 100) ax3.set_yticks(10**np.arange(low_lim, 2, dtype="float64")) ax3.tick_params(labelsize=axes_fontsize) ax3.tick_params(axis="x", pad=xtick_pad) freq_precipitating_points[freq_precipitating_points == 0] = np.nan freq_cwv[freq_cwv == 0] = np.nan # ax3.errorbar(bin_center, freq_precipitating_points, xerr=0, yerr=errorbar_precip_points.squeeze(), ls='none', color='black') ax3.scatter( bin_center, freq_cwv, color=line_color[0], label=data_name.split(":")[0] + ": all", ) ax3.scatter( bin_center, freq_precipitating_points, edgecolor="none", facecolor=line_color[1], s=marker_size, zorder=3, label=data_name.split(":")[0] + ": precip $>$ 0.5 mm/hr ", ) ax3.set_ylabel("PDF", fontsize=axes_fontsize) ax3.set_xlabel("CWV (mm)", fontsize=axes_fontsize) ax3.set_axisbelow(True) # create legend legend_handles, legend_labels = ax3.get_legend_handles_labels() ax3.legend( legend_handles, legend_labels, loc="upper left", bbox_to_anchor=(0.1, 0.95), fontsize=legend_fontsize, scatterpoints=1, handlelength=0, labelspacing=0, borderpad=0, borderaxespad=0, frameon=False, ) # set layout to tight (so that space between figures is minimized) # plt.tight_layout() plt.suptitle("Convection Onset Metrics" + " at " + sitename, y=1.15, fontweight="bold") plt.title(title, ha="left", x=-2, y=0.98) # save figure # mp.savefig(output_path +'/figures/conv_diagnostics_'+test+'_'+sites[0]+'.png', transparent=True, bbox_inches='tight') # Save the figure. output_file_name = parameter.output_file for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join(get_output_dir(parameter.current_set, parameter), output_file_name + "." + f) plt.savefig(fnm, transparent=True, bbox_inches="tight") # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), output_file_name + "." + f, ) print("Plot saved in: " + fnm) plt.close()
def plot(period_new, parameter, test, ref): label_size = 14 fig = plt.figure(figsize=(14, 14)) months = np.minimum(ref["qbo"].shape[0], test["qbo"].shape[0]) x_test, y_test = np.meshgrid(np.arange(0, months), test["level"]) x_ref, y_ref = np.meshgrid(np.arange(0, months), ref["level"]) cmap2 = plt.cm.RdBu_r color_levels0 = np.arange(-50, 51, 100.0 / 20.0) # Panel 0 (Top Left) x = dict(axis_range=[0, months], axis_scale="linear", data=x_test, label=" ") y = dict(axis_range=[100, 1], axis_scale="log", data=y_test, label="hPa") z = dict(data=test["qbo"].T[:, :months]) title = "{} U [{}] 5S-5N ({})".format(test["name"], "m/s", parameter.test_yrs) ax0 = plot_panel( # noqa 0, fig, "contourf", label_size, title, x, y, z=z, plot_colors=cmap2, color_levels=color_levels0, color_ticks=[-50, -25, -5, 5, 25, 50], ) # Panel 1 (Middle Left) x = dict(axis_range=[0, months], axis_scale="linear", data=x_ref, label="month") y = dict(axis_range=[100, 1], axis_scale="log", data=y_ref, label="hPa") z = dict(data=ref["qbo"].T[:, :months]) title = "{} U [{}] 5S-5N ({})".format(ref["name"], "m/s", parameter.ref_yrs) plot_panel( 1, fig, "contourf", label_size, title, x, y, z=z, plot_colors=cmap2, color_levels=color_levels0, color_ticks=[-50, -25, -5, 5, 25, 50], ) # Panel 2 (Top/Middle Right) x = dict( axis_range=[0, 30], axis_scale="linear", data=test["amplitude"][:], data_label=test["name"], data2=ref["amplitude"][:], data2_label=ref["name"], label="Amplitude (m/s)", ) y = dict( axis_range=[100, 1], axis_scale="log", data=test["level"][:], data2=ref["level"][:], label="Pressure (hPa)", ) title = "QBO Amplitude \n (period = 20-40 months)" plot_panel(2, fig, "line", label_size, title, x, y) # Panel 3 (Bottom) x = dict( axis_range=[0, 50], axis_scale="linear", data=period_new, data_label=test["name"], data2=period_new, data2_label=ref["name"], label="Period (months)", ) y = dict( axis_range=[-1, 25], axis_scale="linear", data=test["amplitude_new"], data2=ref["amplitude_new"], label="Amplitude (m/s)", ) title = "QBO Spectral Density (Eq. 18-22 hPa zonal winds)" plot_panel(3, fig, "line", label_size, title, x, y) plt.tight_layout() # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.97, fontsize=15) # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/qbo/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/qbo/{parameter.case_id} original_output_dir = get_output_dir(parameter.current_set, parameter, ignore_container=True) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file is defined in e3sm_diags/driver/qbo_driver.py # {parameter.results_dir}/qbo/{parameter.case_id}/{parameter.output_file} file_path = os.path.join(output_dir, parameter.output_file) # {parameter.orig_results_dir}/qbo/{parameter.case_id}/{parameter.output_file} original_file_path = os.path.join(original_output_dir, parameter.output_file) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix print("Plot saved in: " + original_plot_file_path) # TODO: The subplots don't come out so nicely. Same for ENSO Diags # See Issue 294 # Save individual subplots for f in parameter.output_format_subplot: # i = 0 # for ax in [ax0, ax1, ax2, ax3]: # # Extent of subplot # # https://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib # extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) # # Save subplot # subplot_suffix = ('.%i.' % i) + f # subplot_file_path = file_path + subplot_suffix # plt.savefig(subplot_file_path, bbox_inches=extent.expanded(1.1, 1.2)) # i += 1 # # Get the filename that the user has passed in and display that. # # When running in a container, the paths are modified. # original_subplot_file_path = original_file_path + subplot_suffix # print('Sub-plot saved in: ' + original_subplot_file_path) page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot subplot_suffix = (".%i." % i) + f subplot_file_path = file_path + subplot_suffix plt.savefig(subplot_file_path, bbox_inches=extent) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_subplot_file_path = original_file_path + subplot_suffix print("Sub-plot saved in: " + original_subplot_file_path) i += 1 plt.close()
def plot_annual_scatter(xs, ys, zs, parameter): # Position and sizes of subplot axes in page coordinates (0 to 1) # (left, bottom, width, height) in page coordinates panel = [(0.0900, 0.2000, 0.7200, 0.6000)] fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) ax = fig.add_axes(panel[0]) cmap = plt.get_cmap("jet") ax.scatter(xs, ys, label="Scatterplot", marker="o", s=10, c=zs, cmap=cmap) r, _ = scipy.stats.pearsonr(xs, ys) r2 = r * r r2_str = "{0:.2f}".format(r2) bounds = [0.01, 100000] ax.plot(bounds, bounds, color="red", linestyle="-") ax.set_xscale("log") ax.set_yscale("log") ax.set_xlabel( "{} streamflow ($m^3$/$s$)".format(parameter.reference_title), fontsize=12, ) ax.set_ylabel("{} streamflow ($m^3$/$s$)".format(parameter.test_title), fontsize=12) ax.set_xlim(bounds[0], bounds[1]) ax.set_ylim(bounds[0], bounds[1]) ax.tick_params(axis="both", labelsize=12) # Color bar # Position and sizes of subplot axes in page coordinates (0 to 1) # (left, bottom, width, height) in page coordinates cbax = fig.add_axes( (panel[0][0] + 0.7535, panel[0][1] + 0.0515, 0.0326, 0.1792 * 2) ) cbar_label = "Drainage area bias (%)" cbar = fig.colorbar(matplotlib.cm.ScalarMappable(cmap=cmap), cax=cbax) cbar.ax.set_ylabel(cbar_label, fontsize=12) w, h = get_ax_size(fig, cbax) zs_max = np.ceil(np.max(zs)) zs_min = np.floor(np.min(zs)) step_size = (zs_max - zs_min) // 5 try: ticks = np.arange(zs_min, zs_max + step_size, step_size) cbar.ax.set_yticklabels(ticks) except ValueError: # `zs` has invalid values (likely from no area_upstream being found). # Just use default colorbar. pass cbar.ax.tick_params(labelsize=12.0, length=0) # Figure title if parameter.main_title_annual_scatter == "": main_title_annual_scatter = "Annual mean streamflow\n{} vs {}".format( parameter.test_title, parameter.reference_title ) else: main_title_annual_scatter = parameter.main_title_annual_scatter ax.set_title(main_title_annual_scatter, loc="center", y=1.05, fontsize=15) legend_title = "$R^2$={}, (n={})".format(r2_str, xs.shape[0]) ax.legend(handles=[], title=legend_title, loc="upper left", prop={"size": 12}) # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/streamflow/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/streamflow/{parameter.case_id} original_output_dir = get_output_dir( parameter.current_set, parameter, ignore_container=True ) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file_annual_scatter is defined in e3sm_diags/parameter/streamflow_parameter.py # {parameter.results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_annual_scatter} file_path = os.path.join(output_dir, parameter.output_file_annual_scatter) # {parameter.orig_results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_annual_scatter} original_file_path = os.path.join( original_output_dir, parameter.output_file_annual_scatter ) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix print("Plot saved in: " + original_plot_file_path) plt.close()
def plot_annual_map(export, bias, parameter): if parameter.backend not in ["cartopy", "mpl", "matplotlib"]: return # Position and sizes of subplot axes in page coordinates (0 to 1) # (left, bottom, width, height) in page coordinates panel = [ (0.1691, 0.6810, 0.6465, 0.2258), (0.1691, 0.3961, 0.6465, 0.2258), (0.1691, 0.1112, 0.6465, 0.2258), ] # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) proj = ccrs.PlateCarree(central_longitude=0) # First panel plot_panel_annual_map(0, fig, proj, export, bias, panel, parameter) # Second panel plot_panel_annual_map(1, fig, proj, export, bias, panel, parameter) # Third panel plot_panel_annual_map(2, fig, proj, export, bias, panel, parameter) # Figure title fig.suptitle(parameter.main_title_annual_map, x=0.5, y=0.97, fontsize=15) # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/streamflow/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/streamflow/{parameter.case_id} original_output_dir = get_output_dir( parameter.current_set, parameter, ignore_container=True ) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file_annual_map is defined in e3sm_diags/parameter/streamflow_parameter.py # {parameter.results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_annual_map} file_path = os.path.join(output_dir, parameter.output_file_annual_map) # {parameter.orig_results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_annual_map} original_file_path = os.path.join( original_output_dir, parameter.output_file_annual_map ) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix # Always print, even without `parameter.print_statements` print("Plot saved in: " + original_plot_file_path) # Save individual subplots for f in parameter.output_format_subplot: page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list((subpage * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot subplot_suffix = ".%i." % i + f subplot_file_path = file_path + subplot_suffix plt.savefig(subplot_file_path, bbox_inches=extent) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_subplot_file_path = original_file_path + subplot_suffix # Always print, even without `parameter.print_statements` print("Sub-plot saved in: " + original_subplot_file_path) i += 1 plt.close()
def plot(test, ref, parameter, basin_dict): test_metrics = test["metrics"] ref_metrics = ref["metrics"] test_num_year = test_metrics["num_years"] ref_num_year = ref_metrics["num_years"] test_name = parameter.test_name ref_name = parameter.ref_name # TC intensity of each basins fig, axes = plt.subplots(2, 3, figsize=(12, 7), sharex=True, sharey=True) fig.subplots_adjust(hspace=0.4, wspace=0.15) axes = axes.ravel() ace_ref = [] ace_test = [] num_ref = [] num_test = [] for ifig, (basin, basin_info) in enumerate(basin_dict.items()): ace_ref.append(ref_metrics[basin][0]) ace_test.append(test_metrics[basin][0]) num_ref.append(ref_metrics[basin][3]) num_test.append(test_metrics[basin][3]) ax = axes[ifig] ax.plot( np.arange(1, 7), test_metrics[basin][1] / test_num_year, "--k", linewidth=2, label="Test", ) ax.plot( np.arange(1, 7), ref_metrics[basin][1] / ref_num_year, "k", linewidth=2, label="Ref", ) ax.legend() ax.set_title(basin_info[0]) ax.set_ylabel("TCs per year") plt.xticks([1, 2, 3, 4, 5, 6], ["Cat0", "Cat1", "Cat2", "Cat3", "Cat4", "Cat5"]) ax.xaxis.set_tick_params(labelbottom=True) plt.suptitle( "Test: {}".format(test_name) + "\n" + "Ref: {}".format(ref_name), ha="left", x=0.1, y=0.99, ) output_file_name = "tc-intensity" for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) print("Plot saved in: " + fnm) plt.close() # TC frequency of each basins fig = plt.figure(figsize=(12, 7)) ax = fig.add_subplot(111) N = 6 ind = np.arange(N) # the x locations for the groups width = 0.27 ref_vals = num_ref / np.sum(num_ref) rects1 = ax.bar(ind + width / 2, ref_vals, width, color="darkgrey") test_vals = num_test / np.sum(num_test) rects2 = ax.bar(ind - width / 2, test_vals, width, color="black") print( "total number based on 6 basins", np.sum(num_test), num_test, ) ax.set_xticks(ind) ax.set_xticklabels(( "North Atlantic", "Northwest Pacific", "Eastern Pacific", "North Indian", "South Indian", "South Pacific", )) ax.legend( (rects2[0], rects1[0]), ( "{}: (~{})storms per year".format(test_name, int( np.sum(num_test))), "{}: (~{}) storms per year".format(ref_name, int(np.sum(num_ref))), ), ) ax.set_ylabel("Fraction") ax.set_title("Relative frequency of TCs for each ocean basins") output_file_name = "tc-frequency" for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) print("Plot saved in: " + fnm) plt.close() fig1 = plt.figure(figsize=(12, 6)) ax = fig1.add_subplot(111) N = 6 ind = np.arange(N) # the x locations for the groups width = 0.27 ref_vals = ace_ref / np.sum(ace_ref) rects2 = ax.bar(ind - width / 2, ref_vals, width, color="black") test_vals = ace_test / np.sum(ace_test) rects1 = ax.bar(ind + width / 2, test_vals, width, color="darkgrey") ax.set_xticks(ind) ax.set_xticklabels(( "North Atlantic", "Northwest Pacific", "Eastern Pacific", "North Indian", "South Indian", "South Pacific", )) ax.legend((rects2[0], rects1[0]), (ref_name, test_name)) ax.set_ylabel("Fraction") ax.set_title( "Distribution of accumulated cyclone energy (ACE) among various ocean basins" ) output_file_name = "ace-distribution" for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) print("Plot saved in: " + fnm) plt.close() fig, axes = plt.subplots(2, 3, figsize=(12, 6), sharex=True, sharey=True) fig.subplots_adjust(hspace=0.4, wspace=0.15) axes = axes.ravel() for ifig, (basin, basin_info) in enumerate(basin_dict.items()): ax = axes[ifig] ax.plot(np.arange(1, 13), ref_metrics[basin][2], "k", linewidth=2, label="Test") ax.plot( np.arange(1, 13), test_metrics[basin][2], "--k", linewidth=2, label="Ref", ) ax.legend() ax.set_title(basin_info[0]) ax.set_ylabel("Fraction") plt.xticks( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], ) ax.xaxis.set_tick_params(labelbottom=True) plt.suptitle( "Test: {}".format(test_name) + "\n" + "Ref: {}".format(ref_name), ha="left", x=0.1, y=0.99, ) output_file_name = "tc-frequency-annual-cycle" for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) print("Plot saved in: " + fnm) plt.close() ########################################################## # Plot TC tracks density plot_map(test, ref, "aew", parameter) # Plot AEW density plot_map(test, ref, "cyclone", parameter)
def plot_scatter(x, y, parameter): fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) test_color = "black" ref_color = "red" test_title = "Test" if parameter.test_title == "" else parameter.test_title if parameter.test_name_yrs: test_title += " : {}".format(parameter.test_name_yrs) ref_title = ( "Reference" if parameter.reference_title == "" else parameter.reference_title ) if parameter.ref_name_yrs: ref_title += " : {}".format(parameter.ref_name_yrs) # https://stackoverflow.com/questions/14827650/pyplot-scatter-plot-marker-size plt.scatter( x["test"], y["test"], label=test_title, color=test_color, marker="s", s=8, ) plt.scatter(x["ref"], y["ref"], label=ref_title, color=ref_color, marker="o", s=8) for value_type in ["test", "ref"]: if value_type == "test": type_str = "Test" type_color = test_color x_range = (min(x["test"]), max(x["test"])) else: type_str = "Reference" type_color = ref_color x_range = (min(x["ref"]), max(x["ref"])) # https://stackoverflow.com/questions/35091879/merge-2-arrays-vertical-to-tuple-numpy # Two parallel lists of values values = np.array((x[value_type], y[value_type])) # Zip the values together (i.e., list of (x,y) instead of (list of x, list of y) values = values.T if y["var"] == "TAUX": value_strs = [""] else: value_strs = ["positive ", "negative "] for value_str in value_strs: # https://stackoverflow.com/questions/24219841/numpy-where-on-a-2d-matrix if value_str == "positive ": # For all rows (x,y), choose the rows where x > 0 rows = np.where(values[:, 0] > 0) smaller_x_range = (0, x_range[1]) linestyle = "-" elif value_str == "negative ": # For all rows (x,y), choose the rows where x < 0 rows = np.where(values[:, 0] < 0) smaller_x_range = (x_range[0], 0) linestyle = "--" elif value_str == "": rows = None smaller_x_range = x_range linestyle = "-" if rows: # Get the filtered zip (list of (x,y) where x > 0 or x < 0) filtered_values = values[rows] else: filtered_values = values # Get the filtered parallel lists (i.e., (list of x, list of y)) filtered_values = filtered_values.T # https://stackoverflow.com/questions/19068862/how-to-overplot-a-line-on-a-scatter-plot-in-python b, m = polyfit(filtered_values[0], filtered_values[1], 1) label = "Linear fit for %sTS anomalies: %s (slope = %.2f)" % ( value_str, type_str, m, ) ys = [b + m * x for x in smaller_x_range] plt.plot( smaller_x_range, ys, label=label, color=type_color, linestyle=linestyle, ) max_test = max(abs(min(y["test"])), abs(max(y["test"]))) max_ref = max(abs(min(y["ref"])), abs(max(y["ref"]))) max_value = max(max_test, max_ref) + 1 plt.ylim(-max_value, max_value) plt.xlabel("{} anomaly ({})".format(x["var"], x["units"])) plt.ylabel("{} anomaly ({})".format(y["var"], y["units"])) plt.legend() # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/enso_diags/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/enso_diags/{parameter.case_id} original_output_dir = get_output_dir( parameter.current_set, parameter, ignore_container=True ) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file is defined in e3sm_diags/driver/enso_diags_driver.py # {parameter.results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} file_path = os.path.join(output_dir, parameter.output_file) # {parameter.orig_results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} original_file_path = os.path.join(original_output_dir, parameter.output_file) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.93, fontsize=15) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix print("Plot saved in: " + original_plot_file_path) plt.close()
def plot_map( reference, test, diff, metrics_dict, ref_confidence_levels, test_confidence_levels, parameter, ): if parameter.backend not in ["cartopy", "mpl", "matplotlib"]: return # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) # Use 179.99 as central longitude due to https://github.com/SciTools/cartopy/issues/946 # proj = ccrs.PlateCarree(central_longitude=180) proj = ccrs.PlateCarree(central_longitude=179.99) # Use non-regridded test and ref for stats, # so we have the original stats displayed # First panel plot_panel_map( 0, fig, proj, test, parameter.contour_levels, parameter.test_colormap, (parameter.test_name_yrs, parameter.test_title, test.units), parameter, conf=test_confidence_levels, stats=metrics_dict["test"], ) # Second panel plot_panel_map( 1, fig, proj, reference, parameter.contour_levels, parameter.reference_colormap, (parameter.ref_name_yrs, parameter.reference_title, reference.units), parameter, conf=ref_confidence_levels, stats=metrics_dict["ref"], ) # Third panel plot_panel_map( 2, fig, proj, diff, parameter.diff_levels, parameter.diff_colormap, (None, parameter.diff_title, test.units), parameter, stats=metrics_dict["diff"], ) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.97, fontsize=15) # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/enso_diags/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/enso_diags/{parameter.case_id} original_output_dir = get_output_dir( parameter.current_set, parameter, ignore_container=True ) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file is defined in e3sm_diags/driver/enso_diags_driver.py # {parameter.results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} file_path = os.path.join(output_dir, parameter.output_file) # {parameter.orig_results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} original_file_path = os.path.join(original_output_dir, parameter.output_file) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix print("Plot saved in: " + original_plot_file_path) # Save individual subplots for f in parameter.output_format_subplot: page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot subplot_suffix = ".%i." % (i) + f subplot_file_path = file_path + subplot_suffix plt.savefig(subplot_file_path, bbox_inches=extent) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_subplot_file_path = original_file_path + subplot_suffix print("Sub-plot saved in: " + original_subplot_file_path) i += 1 plt.close()
def plot(test_tmax, test_amp, ref_tmax, ref_amp, parameter): if parameter.backend not in ["cartopy", "mpl", "matplotlib"]: return # Create figure, projection fig = plt.figure(figsize=[8.5, 8.5], dpi=parameter.dpi) proj = ccrs.PlateCarree(central_longitude=180) # First panel plot_panel( 0, fig, proj, test_tmax, test_amp, ref_amp, (parameter.test_name_yrs, parameter.test_title), parameter, ) # Second panel plot_panel( 1, fig, proj, ref_tmax, ref_amp, ref_amp, (parameter.ref_name_yrs, parameter.reference_title), parameter, ) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.9, fontsize=14) # Prepare to save figure # get_output_dir => {parameter.results_dir}/{set_name}/{parameter.case_id} # => {parameter.results_dir}/enso_diags/{parameter.case_id} output_dir = get_output_dir(parameter.current_set, parameter) if parameter.print_statements: print("Output dir: {}".format(output_dir)) # get_output_dir => {parameter.orig_results_dir}/{set_name}/{parameter.case_id} # => {parameter.orig_results_dir}/enso_diags/{parameter.case_id} original_output_dir = get_output_dir(parameter.current_set, parameter, ignore_container=True) if parameter.print_statements: print("Original output dir: {}".format(original_output_dir)) # parameter.output_file is defined in e3sm_diags/driver/enso_diags_driver.py # {parameter.results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} file_path = os.path.join(output_dir, parameter.output_file) # {parameter.orig_results_dir}/enso_diags/{parameter.case_id}/{parameter.output_file} original_file_path = os.path.join(original_output_dir, parameter.output_file) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] plot_suffix = "." + f plot_file_path = file_path + plot_suffix plt.savefig(plot_file_path) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_plot_file_path = original_file_path + plot_suffix print("Plot saved in: " + original_plot_file_path) # Save individual subplots for f in parameter.output_format_subplot: page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot subplot_suffix = ".%i." % (i) + f subplot_file_path = file_path + subplot_suffix plt.savefig(subplot_file_path, bbox_inches=extent) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. original_subplot_file_path = original_file_path + subplot_suffix print("Sub-plot saved in: " + original_subplot_file_path) i += 1 plt.close()
def plot(reference, test, diff, metrics_dict, parameter): # Create figure fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) # Top panel ax1 = fig.add_axes(panel[0]) ax1.plot(test.getLatitude()[:], ma.squeeze(test.asma()), "k", linewidth=2) ax1.plot( reference.getLatitude()[:], ma.squeeze(reference.asma()), "r", linewidth=2, ) ax1.set_xticks([-90, -60, -30, 0, 30, 60, 90]) ax1.set_xlim(-90, 90) ax1.tick_params(labelsize=11.0, direction="out", width=1) ax1.xaxis.set_ticks_position("bottom") ax1.set_ylabel(test.long_name + " (" + test.units + ")") test_title = "Test" if parameter.test_title == "" else parameter.test_title test_title += " : {}".format(parameter.test_name_yrs) ref_title = ("Reference" if parameter.reference_title == "" else parameter.reference_title) ref_title += " : {}".format(parameter.ref_name_yrs) fig.text( panel[0][0], panel[0][1] + panel[0][3] + 0.03, test_title, ha="left", fontdict=plotSideTitle, color="black", ) fig.text( panel[0][0], panel[0][1] + panel[0][3] + 0.01, ref_title, ha="left", fontdict=plotSideTitle, color="red", ) # Bottom panel ax2 = fig.add_axes(panel[1]) ax2.plot(diff.getLatitude()[:], ma.squeeze(diff.asma()), "k", linewidth=2) ax2.axhline(y=0, color="0.5") ax2.set_title(parameter.diff_title, fontdict=plotSideTitle, loc="center") ax2.set_xticks([-90, -60, -30, 0, 30, 60, 90]) ax2.set_xlim(-90, 90) ax2.tick_params(labelsize=11.0, direction="out", width=1) ax2.xaxis.set_ticks_position("bottom") ax2.set_ylabel(test.long_name + " (" + test.units + ")") # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.95, fontsize=18) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file + "." + f, ) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file + "." + f, ) print("Plot saved in: " + fnm) # Save individual subplots for f in parameter.output_format_subplot: fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file, ) page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot fname = fnm + ".%i." % (i) + f plt.savefig(fname, bbox_inches=extent) orig_fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file, ) fname = orig_fnm + ".%i." % (i) + f print("Sub-plot saved in: " + fname) i += 1 plt.close()
def plot(var, regions_to_data, parameter): # Data is a list based on the len of the regions parameter. # Each element is a tuple with ref data, # test data, and metrics for that region. # plot time series line_color = ["r", "b", "g", "m", "c", "y"] # Position and sizes of subplot axes in page coordinates (0 to 1) # The dimensions [left, bottom, width, height] of the new axes. All quantities are in fractions of figure width and height. panel = [ (0.1, 0.70, 0.25, 0.225), (0.4, 0.70, 0.25, 0.225), (0.7, 0.70, 0.25, 0.225), (0.1, 0.38, 0.25, 0.225), (0.4, 0.38, 0.25, 0.225), (0.7, 0.38, 0.25, 0.225), (0.1, 0.06, 0.25, 0.225), (0.4, 0.06, 0.25, 0.225), (0.7, 0.06, 0.25, 0.225), ] # Border padding relative to subplot axes for saving individual panels # (left, bottom, right, top) in page coordinates border = (-0.047, -0.06, 0.006, 0.03) # Create the figure. figsize = [17.0, 10] fig = plt.figure(figsize=figsize, dpi=parameter.dpi) start_time = int(parameter.start_yr) end_time = int(parameter.end_yr) num_year = end_time - start_time + 1 s = parameter.test_name_yrs test_name = s.split("(")[0].replace(" ", "") if test_name == "": test_name = "test data" for i_region, data_set_for_region in enumerate(regions_to_data.values()): refs = data_set_for_region.refs test = data_set_for_region.test ax1 = fig.add_axes(panel[i_region]) ax1.plot( test.asma(), "k", linewidth=2, label=test_name + "(mean: {0:.2f}, std: {1:.3f})".format( np.mean(test.asma()), np.std(test.asma())), ) for i_ref, ref in enumerate(refs): ax1.plot( ref.asma(), line_color[i_ref], linewidth=2, label=ref.ref_name + "(mean: {0:.2f}, std: {1:.3f})".format( np.mean(ref.asma()), np.std(ref.asma())), ) x = np.arange(num_year) # do Truncation Division to accommodating long time records if num_year > 19: stepsize = num_year // 10 else: stepsize = 1 ax1.set_xticks(x[::stepsize]) x_ticks_labels = np.arange(start_time, end_time + 1, stepsize) ax1.set_xticklabels(x_ticks_labels, rotation="45", fontsize=8) ax1.set_ylabel(var + " (" + test.units + ")") ax1.set_xlabel("Year") ax1.legend(loc="best", prop={"size": 7}) ax1.set_title(parameter.regions[i_region], fontsize=10) # Figure title. fig.suptitle( "Annual mean " + var + " time series over regions " + parameter.test_name_yrs, x=0.3, y=0.98, fontsize=15, ) # Save the figure. output_file_name = var for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), output_file_name + "." + f, ) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), output_file_name + "." + f, ) print("Plot saved in: " + fnm) # Save individual subplots for f in parameter.output_format_subplot: fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file, ) page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot fname = fnm + ".%i." % (i) + f plt.savefig(fname, bbox_inches=extent) orig_fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file, ) fname = orig_fnm + ".%i." % (i) + f print("Sub-plot saved in: " + fname) i += 1 plt.close()
def plot(reference, test, diff, metrics_dict, parameter): fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) plot_panel( 0, fig, test, parameter.contour_levels, parameter.test_colormap, (parameter.test_name_yrs, parameter.test_title, test.units), parameter, ) plot_panel( 1, fig, reference, parameter.contour_levels, parameter.reference_colormap, (parameter.ref_name_yrs, parameter.reference_title, reference.units), parameter, ) plot_panel( 2, fig, diff, parameter.diff_levels, parameter.diff_colormap, (None, parameter.diff_title, None), parameter, ) fig.suptitle(parameter.main_title, x=0.5, y=0.96, fontsize=18) # Save figure for f in parameter.output_format: f = f.lower().split(".")[-1] fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file + "." + f, ) plt.savefig(fnm) # Get the filename that the user has passed in and display that. # When running in a container, the paths are modified. fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file + "." + f, ) print("Plot saved in: " + fnm) # Save individual subplots for f in parameter.output_format_subplot: fnm = os.path.join( get_output_dir(parameter.current_set, parameter), parameter.output_file, ) page = fig.get_size_inches() i = 0 for p in panel: # Extent of subplot subpage = np.array(p).reshape(2, 2) subpage[1, :] = subpage[0, :] + subpage[1, :] subpage = subpage + np.array(border).reshape(2, 2) subpage = list(((subpage) * page).flatten()) extent = matplotlib.transforms.Bbox.from_extents(*subpage) # Save subplot fname = fnm + ".%i." % (i) + f plt.savefig(fname, bbox_inches=extent) orig_fnm = os.path.join( get_output_dir(parameter.current_set, parameter, ignore_container=True), parameter.output_file, ) fname = orig_fnm + ".%i." % (i) + f print("Sub-plot saved in: " + fname) i += 1 plt.close()