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_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(central_longitude=180) proj = None # 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_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 acme_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_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 acme_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(reference, test, diff, metrics_dict, parameter): vcs_canvas = vcs.init(bg=True, geometry=(parameter.canvas_size_w, parameter.canvas_size_h)) parameter.case_id file_path = os.path.join(acme_diags.INSTALL_PATH, 'polar') vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_7.json')) vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_7_new.json')) template_test = vcs_canvas.gettemplate('plotset7_0_x_0') template_ref = vcs_canvas.gettemplate('plotset7_0_x_1') template_diff = vcs_canvas.gettemplate('plotset7_0_x_2') template_test.title.x = 0.01 template_test.dataname.x = 0.01 template_test.dataname.y = template_test.title.y - 0.02 template_test.data.y1 -= 0.025 template_test.data.y2 -= 0.02 template_ref.title.x = 0.01 template_ref.dataname.x = 0.01 template_ref.dataname.y = template_ref.title.y - 0.02 template_ref.data.y1 -= 0.025 template_ref.data.y2 -= 0.025 template_diff.title.x = 0.01 template_diff.dataname.x = 0.01 template_diff.dataname.y = template_diff.title.y - 0.02 template_diff.data.y1 -= 0.025 template_diff.data.y2 -= 0.025 utils.set_units(test, parameter.test_units) utils.set_units(reference, parameter.reference_units) utils.set_units(diff, parameter.diff_units) test.long_name = parameter.test_title reference.long_name = parameter.reference_title diff.long_name = parameter.diff_title test.id = parameter.test_name_yrs reference.id = parameter.ref_name_yrs diff.id = parameter.diff_name # model and observation graph utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'test') utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'ref') utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'diff') reference_isofill = vcs.getisofill('reference_isofill') reference_isofill.missing = 'grey' reference_isofill.xticlabels1 = { 0: "0", 30: "30$^\circ$E", 60: "60$^\circ$E", 90: "90$^\circ$E", 120: "120$^\circ$E", 150: "150$^\circ$E", 180: "180$^\circ$W", 210: "150$^\circ$W", 240: "120$^\circ$W", 270: "90$^\circ$W", 300: "60$^\circ$W", 330: "30$^\circ$W" } test_isofill = vcs.getisofill('test_isofill') test_isofill.missing = 'grey' test_isofill.xticlabels1 = { 0: "0", 30: "30$^\circ$E", 60: "60$^\circ$E", 90: "90$^\circ$E", 120: "120$^\circ$E", 150: "150$^\circ$E", 180: "180$^\circ$W", 210: "150$^\circ$W", 240: "120$^\circ$W", 270: "90$^\circ$W", 300: "60$^\circ$W", 330: "30$^\circ$W" } diff_isofill = vcs.getisofill('diff_isofill') diff_isofill.missing = 'grey' diff_isofill.xticlabels1 = { 0: "0", 30: "30$^\circ$E", 60: "60$^\circ$E", 90: "90$^\circ$E", 120: "120$^\circ$E", 150: "150$^\circ$E", 180: "180$^\circ$W", 210: "150$^\circ$W", 240: "120$^\circ$W", 270: "90$^\circ$W", 300: "60$^\circ$W", 330: "30$^\circ$W" } if parameter.var_region.lower().find('polar') != -1: reference_isofill.projection = 'polar' test_isofill.projection = 'polar' diff_isofill.projection = 'polar' if parameter.var_region.find('S') != -1: lat_y1 = -90 lat_y2 = -55 elif parameter.var_region.find('N') != -1: lat_y1 = 90 lat_y2 = 50 # this should extracted from selected domain reference_isofill.datawc_y1 = lat_y1 reference_isofill.datawc_y2 = lat_y2 test_isofill.datawc_y1 = lat_y1 # this should extracted from selected domain test_isofill.datawc_y2 = lat_y2 diff_isofill.datawc_y1 = lat_y1 # this should extracted from selected domain diff_isofill.datawc_y2 = lat_y2 utils.set_levels_of_graphics_method(reference_isofill, parameter.contour_levels, reference, test) utils.set_levels_of_graphics_method(test_isofill, parameter.contour_levels, test, reference) utils.set_levels_of_graphics_method(diff_isofill, parameter.diff_levels, diff) if parameter.arrows: reference_isofill.ext_1 = True reference_isofill.ext_2 = True test_isofill.ext_1 = True test_isofill.ext_2 = True diff_isofill.ext_1 = True diff_isofill.ext_2 = True utils.set_colormap_of_graphics_method(vcs_canvas, parameter.reference_colormap, reference_isofill, parameter) utils.set_colormap_of_graphics_method(vcs_canvas, parameter.test_colormap, test_isofill, parameter) utils.set_colormap_of_graphics_method(vcs_canvas, parameter.diff_colormap, diff_isofill, parameter) vcs_canvas.plot(utils.add_cyclic(test), template_test, test_isofill) vcs_canvas.plot(utils.add_cyclic(reference), template_ref, reference_isofill) vcs_canvas.plot(utils.add_cyclic(diff), template_diff, diff_isofill) utils.plot_rmse_and_corr(textcombined_objs, vcs_canvas, metrics_dict) # Plotting the main title main_title = utils.managetextcombined(textcombined_objs, 'main_title', 'main_title', vcs_canvas) main_title.string = parameter.main_title main_title.y = [0.985] # for some reason, this needs to be before a call to vcs_canvas.plot() vcs_canvas.portrait() vcs_canvas.plot(main_title) if not parameter.logo: vcs_canvas.drawlogooff() fnm = os.path.join(get_output_dir(parameter.current_set, parameter), parameter.output_file) for f in parameter.output_format: f = f.lower().split('.')[-1] if f == 'png': vcs_canvas.png(fnm) elif f == 'pdf': vcs_canvas.pdf(fnm) elif f == 'svg': vcs_canvas.svg(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) print('Plot saved in: ' + fnm + '.' + f) vcs_canvas.clear()
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 acme_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): vcs_canvas = vcs.init(bg=True, geometry=(parameter.canvas_size_w, parameter.canvas_size_h)) parameter.case_id reference = rotate_180(reference) test = rotate_180(test) diff = rotate_180(diff) file_path = os.path.join(acme_diags.INSTALL_PATH, 'zonal_mean_2d') vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_4.json')) vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_4_new.json')) template_test = vcs_canvas.gettemplate('plotset4_0_x_0') template_ref = vcs_canvas.gettemplate('plotset4_0_x_1') template_diff = vcs_canvas.gettemplate('plotset4_0_x_2') utils.set_units(test, parameter.test_units) utils.set_units(reference, parameter.reference_units) utils.set_units(diff, parameter.diff_units) test.long_name = parameter.test_title reference.long_name = parameter.reference_title diff.long_name = parameter.diff_title test.id = parameter.test_name_yrs reference.id = parameter.ref_name_yrs diff.id = parameter.diff_name # model and observation graph utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'test') utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'ref') utils.plot_min_max_mean(textcombined_objs, vcs_canvas, metrics_dict, 'diff') reference_isofill = vcs.getisofill('reference_isofill') reference_isofill.missing = 'grey' reference = log_yaxis(reference, reference_isofill) test_isofill = vcs.getisofill('test_isofill') test_isofill.missing = 'grey' test = log_yaxis(test, test_isofill) diff_isofill = vcs.getisofill('diff_isofill') diff_isofill.missing = 'grey' diff = log_yaxis(diff, diff_isofill) utils.set_levels_of_graphics_method(reference_isofill, parameter.contour_levels, reference, test) utils.set_levels_of_graphics_method(test_isofill, parameter.contour_levels, test, reference) utils.set_levels_of_graphics_method(diff_isofill, parameter.diff_levels, diff) if parameter.arrows: reference_isofill.ext_1 = True reference_isofill.ext_2 = True test_isofill.ext_1 = True test_isofill.ext_2 = True diff_isofill.ext_1 = True diff_isofill.ext_2 = True utils.set_colormap_of_graphics_method(vcs_canvas, parameter.reference_colormap, reference_isofill, parameter) utils.set_colormap_of_graphics_method(vcs_canvas, parameter.test_colormap, test_isofill, parameter) utils.set_colormap_of_graphics_method(vcs_canvas, parameter.diff_colormap, diff_isofill, parameter) vcs_canvas.plot(test, template_test, test_isofill) vcs_canvas.plot(reference, template_ref, reference_isofill) vcs_canvas.plot(diff, template_diff, diff_isofill) utils.plot_rmse_and_corr(textcombined_objs, vcs_canvas, metrics_dict) # Plotting the main title main_title = utils.managetextcombined(textcombined_objs, 'main_title', 'main_title', vcs_canvas) main_title.string = parameter.main_title # for some reason, this needs to be before a call to vcs_canvas.plot() vcs_canvas.portrait() vcs_canvas.plot(main_title) if not parameter.logo: vcs_canvas.drawlogooff() fnm = os.path.join(get_output_dir(parameter.current_set, parameter), parameter.output_file) for f in parameter.output_format: f = f.lower().split('.')[-1] if f == 'png': vcs_canvas.png(fnm) elif f == 'pdf': vcs_canvas.pdf(fnm) elif f == 'svg': vcs_canvas.svg(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) print('Plot saved in: ' + fnm + '.' + f) vcs_canvas.clear()
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_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 = min(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. / 20.) # 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) title = '{} U 5S-5N ({})'.format(test['name'], parameter.test_yrs) ax0 = plot_panel(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) title = '{} U 5S-5N ({})'.format(ref['name'], parameter.ref_yrs) ax1 = 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)' ax2 = 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)' ax3 = 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 acme_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(reference, test, diff, metrics_dict, parameter): # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) # Create projection if parameter.var_region.find('N') != -1: pole = 'N' proj = ccrs.NorthPolarStereo(central_longitude=0) elif parameter.var_region.find('S') != -1: pole = 'S' proj = ccrs.SouthPolarStereo(central_longitude=0) # First two panels min1 = metrics_dict['test']['min'] mean1 = metrics_dict['test']['mean'] max1 = metrics_dict['test']['max'] if test.count() > 1: plot_panel(0, fig, proj, pole, 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'] if reference.count() > 1: plot_panel(1, fig, proj, pole, 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'] if diff.count() > 1: plot_panel(2, fig, proj, pole, diff, parameter.diff_levels, parameter.diff_colormap, [None, parameter.diff_title, None], parameter, stats=(max3, mean3, min3, r, c)) # Figure title fig.suptitle(parameter.main_title, x=0.5, y=0.97, 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(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()
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 acme_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 acme_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(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(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(reference, test, diff, _, parameter): # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) plot_panel( 0, fig, _, test, parameter.contour_levels, "rainbow", (parameter.test_name_yrs, parameter.test_title, test.units), parameter, ) plot_panel( 1, fig, _, reference, parameter.contour_levels, "rainbow", (parameter.ref_name_yrs, parameter.reference_title, test.units), parameter, ) plot_panel( 2, fig, _, diff, parameter.diff_levels, parameter.diff_colormap, (parameter.diff_name, parameter.diff_title, test.units), parameter, ) # min2 = metrics_dict['ref']['min'] # mean2 = metrics_dict['ref']['mean'] # max2 = metrics_dict['ref']['max'] # plot_panel(1, fig, proj, reference, parameter.contour_levels, 'viridis', # (parameter.reference_name,parameter.reference_title,reference.units),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, 'RdBu_r', (None,parameter.diff_title,None), 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_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_seasonality_map(export, 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.0900, 0.5500, 0.7200, 0.3000), (0.0900, 0.1300, 0.7200, 0.3000), ] # Create figure, projection fig = plt.figure(figsize=parameter.figsize, dpi=parameter.dpi) proj = ccrs.PlateCarree(central_longitude=0) # test and ref color lists # Selected from 'hsv' colormap: color_list = [(0.05, 0.00, 0.99), (0.03, 0.30, 0.98), (0.12, 0.92, 0.99), (0.13, 1.00, 0.65), (0.14, 1.00, 0.05), (0.98, 0.99, 0.04), (0.99, 0.67, 0.04), (0.99, 0.34, 0.03), (0.99, 0.07, 0.03), (0.99, 0.00, 0.53), (0.68, 0.00, 1.00), (0.29, 0.00, 1.00)] # First panel plot_panel_seasonality_map('test', fig, proj, export, color_list, panel, parameter) # Second panel plot_panel_seasonality_map('ref', fig, proj, export, color_list, panel, parameter) # Figure title fig.suptitle(parameter.main_title_seasonality_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_seasonality_map is defined in acme_diags/parameter/streamflow_parameter.py # {parameter.results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_seasonality_map} file_path = os.path.join(output_dir, parameter.output_file_seasonality_map) # {parameter.orig_results_dir}/streamflow/{parameter.case_id}/{parameter.output_file_seasonality_map} original_file_path = os.path.join(original_output_dir, parameter.output_file_seasonality_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(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 plotTitle = {'fontsize': 8.5} plotSideTitle = {'fontsize': 6.5} 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 years = s[s.find("(")+1:s.find(")")] test_name = s.split('(')[0].replace(' ', '') if test_name is '': 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(ref, test, diff, metrics_dict, parameters): vcs_canvas = vcs.init(bg=True, geometry=( parameters.canvas_size_w, parameters.canvas_size_h)) # Line options, see here: https://uvcdat.llnl.gov/documentation/vcs/vcs-10.html # Other options not in the above link: # https://uvcdat.llnl.gov/docs/vcs/graphics/unified1D.html ref_plot_linetype = 0 ref_plot_color = 215 # 6 to 239 ref_plot_width = 3 # 1 to 100 ref_plot_marker = 1 ref_plot_markersize = 1 ref_plot_markercolor = 215 test_plot_linetype = 0 test_plot_color = 1 test_plot_width = 3 test_plot_marker = 1 test_plot_markersize = 1 test_plot_markercolor = 1 diff_plot_linetype = 0 diff_plot_color = 1 diff_plot_width = 3 diff_plot_marker = 1 diff_plot_markersize = 1 diff_plot_markercolor = 1 file_path = os.path.join(acme_diags.INSTALL_PATH, 'zonal_mean_xy') vcs_canvas.scriptrun(os.path.join(file_path, 'plot_set_3.json')) utils.set_units(test, parameters.test_units) utils.set_units(ref, parameters.reference_units) utils.set_units(diff, parameters.diff_units) if hasattr(test, 'long_name'): test.long_name = parameters.test_title if parameters.test_title is not '' else test.long_name if hasattr(ref, 'long_name'): ref.long_name = parameters.reference_title if parameters.reference_title is not '' else ref.long_name if hasattr(diff, 'long_name'): diff.long_name = parameters.diff_title if parameters.diff_title is not '' else diff.long_name test.id = str( parameters.test_name_yrs) if parameters.test_name_yrs is not '' else test.id ref.id = str( parameters.ref_name_yrs) if parameters.ref_name_yrs is not '' else ref.id diff.id = str( parameters.diff_name) if parameters.diff_name is not '' else diff.id # use vcs_canvas.show('colormap') to view all colormaps # 6 to 239 are purple to red in rainbow order vcs_canvas.setcolormap('rainbow') ref_test_template = vcs.gettemplate('ref_test_template') ref_test_yaxis_title = managetextcombined( 'ref_test_yaxis_title', 'ref_test_yaxis_title', vcs_canvas) ref_test_yaxis_title.angle = 270 ref_test_yaxis_title.halign = 'center' ref_test_yaxis_title.y = ( ref_test_template.data.y1 + ref_test_template.data.y2) / 2 ref_test_yaxis_title.x = ref_test_template.data.x1 - 0.08 ref_test_yaxis_title.string = test.long_name + ' (' + test.units + ')' vcs_canvas.plot(ref_test_yaxis_title) ref_test_template.legend.priority = 0 ref_test_template.title.priority = 0 # make all of the elements listed have priority = 0 # ref_test_template.blank(["mean", "max", "min", "zvalue", "crtime", "ytic2", "xtic2"]) # the actual box around the plot ref_test_template.box1.x1 = 0.1223 ref_test_template.box1.x2 = 0.96 ref_test_template.box1.y1 = 0.55 ref_test_template.box1.y2 = 0.90 # data (the lines) need to be offset accordingly ref_test_template.data.x1 = 0.1223 ref_test_template.data.x2 = 0.96 ref_test_template.data.y1 = 0.55 ref_test_template.data.y2 = 0.90 # ref_test_template.legend.x1 = 0.88 # ref_test_template.legend.x2 = 0.98 # ref_test_template.legend.y1 = 0.96 # ref_test_template.legend.y2 = 0.88 # ref_test_template.legend.textorientation = 'defright' # ref_test_template.title.x = 0.5 # ref_test_template.title.textorientation = 'defcenter' ref_test_template.units.textorientation = 'defright' ref_test_template.units.x = 0.96 ref_test_template.units.y = 0.91 # labels on xaxis ref_test_template.xlabel1.y = (0.55) - 0.02 # no xlabel1.x attribute # actual ticks on xaxis ref_test_template.xtic1.y1 = (0.55 - 0.005) + 0.01 ref_test_template.xtic1.y2 = (0.55 - 0.005) # name of xaxis # ref_test_template.xname.y += 0.29 # labels on yaxis ref_test_template.ylabel1.x = 0.11 # no ylabel1.y attribute # actual ticks on yaxis ref_test_template.ytic1.x1 = (0.1223 - 0.006) + 0.01 ref_test_template.ytic1.x2 = (0.1223 - 0.006) diff_template = vcs.gettemplate('diff_template') diff_yaxis_title = managetextcombined( 'diff_yaxis_title', 'diff_yaxis_title', vcs_canvas) diff_yaxis_title.angle = 270 diff_yaxis_title.halign = 'center' diff_yaxis_title.y = (diff_template.data.y1 + diff_template.data.y2) / 2 diff_yaxis_title.x = diff_template.data.x1 - 0.08 diff_yaxis_title.string = test.long_name + ' (' + test.units + ')' vcs_canvas.plot(diff_yaxis_title) diff_template.units.textorientation = 'defright' diff_template.units.x += 0.01 diff_template.legend.priority = 0 diff_template.ytic1.x1 = (0.1223 - 0.006) + 0.01 diff_template.ytic1.x2 = (0.1223 - 0.006) diff_template.ylabel1.x = 0.11 # no ylabel1.y attribute diff_template.units.textorientation = 'defright' diff_template.units.x = 0.96 ''' diff_template.box1.y1 -= 0.47 diff_template.box1.y2 -= 0.47 diff_template.data.y1 -= 0.47 diff_template.data.y2 -= 0.47 diff_template.legend.y1 -= 0.47 diff_template.legend.y2 -= 0.47 diff_template.title.y -= 0.47 diff_template.units.y -= 0.47 diff_template.xlabel1.y -= 0.47 diff_template.xtic1.y1 -= 0.47 diff_template.xtic1.y2 -= 0.47 diff_template.xname.y -= 0.47 diff_template.yname.y -= 0.47 ''' ref_line = vcs_canvas.getxvsy('ref_plot') ref_line.datawc_y1 = min(ref.min(), test.min()) ref_line.datawc_y2 = max(ref.max(), test.max()) ref_line.datawc_x1 = -90 ref_line.datawc_x2 = 90 ref_line.xticlabels1 = {-90: "90S", -60: "60S", -30: "30S", 0: "Eq", 30: "30N", 60: "60N", 90: "90N"} test_line = vcs_canvas.getxvsy('test_plot') test_line.datawc_y1 = min(ref.min(), test.min()) test_line.datawc_y2 = max(ref.max(), test.max()) test_line.datawc_x1 = -90 test_line.datawc_x2 = 90 diff_line = vcs_canvas.getxvsy('diff_plot') diff_line.datawc_y1 = diff.min() diff_line.datawc_y2 = diff.max() diff_line.datawc_x1 = -90 diff_line.datawc_x2 = 90 diff_line.xticlabels1 = {-90: "90S", -60: "60S", -30: "30S", 0: "Eq", 30: "30N", 60: "60N", 90: "90N"} # ref_line.line = ref_plot_linetype ref_line.linetype = ref_plot_linetype ref_line.linecolor = ref_plot_color ref_line.linewidth = ref_plot_width ref_line.marker = ref_plot_marker ref_line.markersize = ref_plot_markersize ref_line.markercolor = ref_plot_markercolor # test_line.line = test_plot_linetype test_line.linetype = test_plot_linetype test_line.linecolor = test_plot_color test_line.linewidth = test_plot_width test_line.marker = test_plot_marker test_line.markersize = test_plot_markersize test_line.markercolor = test_plot_markercolor # test_line.smooth = 1 # diff_line.line = diff_plot_linetype diff_line.linetype = diff_plot_linetype diff_line.linecolor = diff_plot_color diff_line.linewidth = diff_plot_width diff_line.marker = diff_plot_marker diff_line.markersize = diff_plot_markersize diff_line.markercolor = diff_plot_markercolor blank_template = vcs_canvas.gettemplate('blank_template') blank_template.legend.priority = 0 blank_template.data.priority = 1 # blank_template.blank() # blank_template.legend.priority = 1 # blank_template.legend.y1 -= 0.05 # blank_template.legend.y2 -= 0.05 # vcs_canvas.plot(ref, ref_line, ref_test_template, xname='Latitude') vcs_canvas.plot(ref, ref_line, ref_test_template) vcs_canvas.plot(test, test_line, blank_template) # vcs_canvas.plot(diff, diff_line, diff_template, xname='Latitude') vcs_canvas.plot(diff, diff_line, diff_template) # Plot the main title main_title = managetextcombined('main_title', 'main_title', vcs_canvas) main_title.string = parameters.main_title # for some reason, this needs to be before a call to vcs_canvas.plot() vcs_canvas.portrait() vcs_canvas.plot(main_title) test_title = managetextcombined('test_title', 'test_title', vcs_canvas) test_title.string = "Test: " + str(parameters.test_name) test_title.color = 1 test_title.x = ref_test_template.data.x1 - 0.05 test_title.y = ref_test_template.data.y2 + 0.045 test_title.height = 12 vcs_canvas.plot(test_title) ref_title = managetextcombined('ref_title', 'ref_title', vcs_canvas) ref_title.string = "Reference: " + str(parameters.reference_name) ref_title.color = 215 ref_title.x = ref_test_template.data.x1 - 0.05 ref_title.y = ref_test_template.data.y2 + 0.025 ref_title.height = 12 vcs_canvas.plot(ref_title) if not parameters.logo: vcs_canvas.drawlogooff() # ref_test_template.script('plot_set_3.json') # blank_template.script('plot_set_3.json') # diff_template.script('plot_set_3.json') # ref_line.script('plot_set_3.json') # test_line.script('plot_set_3.json') # diff_line.script('plot_set_3.json') # main_title.script('plot_set_3.json') # ref_test_yaxis_title.script('plot_set_3.json') # diff_yaxis_title.script('plot_set_3.json') # test_title.script('plot_set_3.json') # ref_title.script('plot_set_3.json') fnm = os.path.join(get_output_dir(parameters.current_set, parameters), parameters.output_file) for f in parameters.output_format: f = f.lower().split('.')[-1] if f == 'png': vcs_canvas.png(fnm) elif f == 'pdf': vcs_canvas.pdf(fnm) elif f == 'svg': vcs_canvas.svg(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(parameters.current_set, parameters, ignore_container=True), parameters.output_file) print('Plot saved in: ' + fnm + '.' + f) vcs_canvas.clear()